<?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>lambda &#8211; Software, Fitness, and Gaming &#8211; Jesse Warden</title>
	<atom:link href="https://jessewarden.com/tag/lambda/feed" rel="self" type="application/rss+xml" />
	<link>https://jessewarden.com</link>
	<description>Software &#124; Fitness &#124; Gaming</description>
	<lastBuildDate>Thu, 15 Feb 2018 19:40:31 +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>lambda &#8211; Software, Fitness, and Gaming &#8211; Jesse Warden</title>
	<link>https://jessewarden.com</link>
	<width>32</width>
	<height>32</height>
</image> 
	<item>
		<title>AWS Adventures: Part 3 – Post Mortem on Lambdas</title>
		<link>https://jessewarden.com/2017/09/aws-adventures-part-3-post-mortem-on-lambdas.html</link>
		
		<dc:creator><![CDATA[JesterXL]]></dc:creator>
		<pubDate>Thu, 28 Sep 2017 00:26:28 +0000</pubDate>
				<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[aws]]></category>
		<category><![CDATA[lambda]]></category>
		<category><![CDATA[serverless]]></category>
		<guid isPermaLink="false">http://jessewarden.com/?p=5359</guid>

					<description><![CDATA[Introduction Friends have asked that I report a from the trenches update on my thoughts on Lambdas. I fell in love about a year ago, so how do I feel now? I&#8217;ll cover the pro&#8217;s and con&#8217;s I faced, what I learned, and what I still don&#8217;t know. Why If you read my previous article [&#8230;]]]></description>
										<content:encoded><![CDATA[<h1>Introduction</h1>
<p>Friends have asked that I report a from the trenches update on my thoughts on Lambdas. I fell in love about a year ago, so how do I feel now? I&#8217;ll cover the pro&#8217;s and con&#8217;s I faced, what I learned, and what I still don&#8217;t know.<br />
<span id="more-5359"></span></p>
<h1>Why</h1>
<p>If you read my previous article on <a href="http://jessewarden.com/2016/12/aws-adventures-part-1-lambda.html">what Lambdas are</a>, and <a href="http://jessewarden.com/2017/01/aws-adventures-part-2-infrastructure-as-code-deploying-a-microservice.html">how you build an automation workflow</a> around them, you&#8217;ll see why I like them. In short, a front end developer with a bit of back-end Node experience can use continuous deployment for working REST services (or non) quickly, without worry of maintenance, or sudden spikes in traffic. I&#8217;m a coder, and with the <a href="https://aws.amazon.com/sdk-for-node-js/">AWS Node</a> and <a href="https://aws.amazon.com/sdk-for-python/">Python SDK</a> , I can code my way onto the cloud vs. learning Unix, various weirdness with Terraform/Chef/Ansible/Docker, etc.</p>
<p>I have Amazon manage my infrastructure so I can focus on coding. I love it.</p>
<h1>Different Environments</h1>
<p>If you utilize multiple AWS accounts and/or environments, the gotchas are basically your permissions. Specifically, IAM roles and what permissions those IAM roles have. If you follow the whole dev/qa/staging/prod etc. life cycle of testing your code in each <a href="https://www.martinfowler.com/articles/continuousIntegration.html#TestInACloneOfTheProductionEnvironment">environment</a> and then &#8220;moving&#8221; to a higher environment once the code passes all testing, you&#8217;ll find you do the same thing here. In my experience, you&#8217;re just testing two things: Can my Lambda use it&#8217;s permissions the same (log to CloudWatch, access a particular S3 bucket, etc) as well as ensuring connectivity that you could of fat fingered somewhere (i.e. the subnet/security group in the Terraform that&#8217;s creating your Lambda isn&#8217;t correct for the prod environment)? Beyond that, everything seems to operate the same between environments which I loved.</p>
<p><strong>Lesson</strong>: As long as you avoid <a href="http://www.continuitysoftware.com/blog/what-is-configuration-drift/">configuration drift</a>, you&#8217;re fine.</p>
<h1>No API Gateway?</h1>
<p>Lambdas are built for burst traffic or the occasional code run for simple services. However, it does NOT require an API Gateway. Meaning, you do not need a URL to have your code run. It truly is a &#8220;function&#8221;, or a bunch of code. How that code is run doesn&#8217;t have to be a URL being put in the web browser.</p>
<p>AWS is flexible. Lambdas are actually functions, not actual &#8220;API&#8217;s&#8221;. Meaning, anything can trigger them; they ARE functions. Files put on an S3 bucket (hard drive), some log messages in CloudWatch that match a string, and even periodic cron jobs managed by AWS. I can personally attest that during the S3 outage last year, when it came back up, not 1 of my messages over a 2 hour period was lost in my CloudWatch cro</p>
<p>More important, though, is that Lambdas can invoke other Lambdas.</p>
<p><strong>Lesson</strong>: Even with AWS, you can code yourself out of any negative situation. :: flexes bicep :: Take a look the triggers that AWS provides for Lambdas. You truly can react to a variety of events.</p>
<h1>Lambda&#8217;s Calling Lambda&#8217;s</h1>
<p>Lambda&#8217;s can invoke other Lambda functions through <a href="https://boto3.readthedocs.io/en/latest/reference/services/lambda.html#Lambda.Client.invoke">lambda.invoke.</a> Given the fact that each Lambda (Python or JavaScript) with a reasonable amount of code runs less than 100 to 200 ms is awesome&#8230; and doesn&#8217;t cost me much since I&#8217;m not running a high TPS in my personal projects, this is great.</p>
<p>Another subtle benefit is that you can call them in either a request / response for a more REST type of feel, or a fire and forget for longer running processes. While I haven&#8217;t been able to have the need yet, I loved playing with the <a href="https://aws.amazon.com/step-functions/">step functions</a> for when you have a bunch of microservices you&#8217;re trying to coordinate in a concurrent fashion.</p>
<h1>Errors and Logging</h1>
<p>Be aware that some connection errors aren&#8217;t verbose. This may be for security reasons. 99% of my &#8220;Lambda can&#8217;t connect to some thing&#8221; all had to do with a misconfigured security group, subnet, or IAM permission. That&#8217;s good to know since those things can be easily automated using Terraform or things like the SDK.</p>
<p>For logging, while Lambdas typically log to CloudWatch by default, make sure you log to a single log stream so you can utilize the console or SDK to more easily find logs in a time window. Searching various log streams with dates in the titles over time to find a particular log is harder if it&#8217;s not in a the same stream name.</p>
<h1>Time Limit</h1>
<p>Years ago, Lambdas were limited to 1 minute. Then they got 5 minutes. 5 minutes is still not enough once you have so much power at your finger tips, heh.</p>
<p>If you run into scenarios where 5 minutes isn&#8217;t enough, you have 2 options:</p>
<ol>
<li>Use <a href="https://aws.amazon.com/step-functions/">step functions</a>. This can be challenging for some developers because it inverses the responsibility of those doing the work to poll for jobs vs. you being responsible to tell them. This helps solve concurrency issues, too.</li>
<li>Use an audit log + <a href="https://docs.aws.amazon.com/AmazonCloudWatch/latest/events/ScheduledEvents.html">CloudWatch cron job</a>. Either use a NoSQL database like <a href="https://aws.amazon.com/dynamodb/">Dynamo</a> or an S3 bucket folder. Your Lambda&#8217;s will do their work, then audit that they &#8220;started and stopped&#8221; with a UUID. This could be a timestamped data entry in Dynamo, or a file in S3 bucket. You then have that long running process make an entry with the same UUID/correlation ID in the same audit log (Dynamo or S3). Finally, you have a CloudWatch cron job launch a Lambda every minute or so to check on the status. When the Lambda finds a stopped job audit entry that matches a start, it can mark the job as successful, error&#8217;d, or timed out based on your criteria. This CloudWatch cron jobs are beast, yes, they can be trusted.</li>
</ol>
<p>&nbsp;</p>
<p>&nbsp;</p>
<p>&nbsp;</p>
<p>&nbsp;</p>
<p>&nbsp;</p>
<p>&nbsp;</p>
<p>&nbsp;</p>
<h1>Deployment</h1>
<p>Deployment is huge contention amongst many developers. I&#8217;m a huge proponent of automating everything with the AWS SDK. Others like to use Terrform/Chef/Ansible, etc. Others like to upload ZIP files through the console.</p>
<p>Whatever method you do, I still encourage the use of existing integration testing solutions. AWS&#8217;s update process is super easy; you&#8217;re literally uploading code to the Lambda directly or an S3 bucket, and &#8220;poof&#8221;, you&#8217;re Lambda is updated. You can use the environment &amp; versioning if you wish. I personally didn&#8217;t like that, though, and instead liked using a <a href="https://martinfowler.com/bliki/BlueGreenDeployment.html">green/blue deployment</a> model where you have 2 Lambdas with a blue/green suffix in the name. When you upload new code, you simply switch the trigger as the last step once all your integration tests have been run. If you screw up, no big deal, it&#8217;s near instant to switch it back without uploading new code.</p>
<p>Things like ping and health checks are still extremely important, as are dry runs. Ping&#8217;s are simply a way of ensuring your Lambda function is there. If it&#8217;s API Gateway, that&#8217;s a URL you can hit to ensure it works. If it&#8217;s an S3 bucket trigger, you can drop a particular filename in a particular place, and your Lambda can respond either there or in CloudWatch. For health checks, this is the most important; it ensures your Lambda can talk to all the required services it needs and report back. This goes hand in hand with a dry run to ensure it can talk to those things, but doesn&#8217;t affect them; like making accidental database entries. Instead, it&#8217;s just ensuring your connectivity (i.e. IAM role permissions, subnet/security groups, VPC&#8217;s) are all correct.</p>
<p>&nbsp;</p>
<h1>Where Do We Go From Here?</h1>
<p>A guy reached out to me on Slack asking for help in Python. He&#8217;s never coded in his life, about my age (38), and manages databases that are recently moved from an on-prem situation to his AWS. He wanted to basically have an alarm (an AWS log event) trigger a Lambda, and if it&#8217;s cause was the database was running out of hard drive, to allocate 50 megs more. I gave him a crash course in Python and what I had learned of AWS and Lambdas, and he was up and running in about a month in prod with a 30 line Python Lambda.</p>
<p>That&#8217;s so awesome.</p>
<p>The people using AWS Batch and other short lived EC2&#8217;s for minutes to seconds worth of work are moving some of that to Lambdas for price reasons. Various Lambdas are in the background, facilitating various logging, monitoring, or reactionary/reactive roles to help functionality in Ops or for developers. It&#8217;s become &#8220;just another tool in the toolbox&#8221;, not some new, shiny thing to not be trusted by the cynics.</p>
<p>We&#8217;re still at the beginning of serverless. It is growing, and more and more people from a variety of skillets want to use them. That&#8217;s telling. If you&#8217;re not doing a lot of server-side development and just frontend websites, I encourage you to take a look at hosting your files on S3 and simply putting CloudWatch in front of it. AWS has a good wizard for this.</p>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>AWS Adventures: Part 1 &#8211; Lambda</title>
		<link>https://jessewarden.com/2016/12/aws-adventures-part-1-lambda.html</link>
		
		<dc:creator><![CDATA[JesterXL]]></dc:creator>
		<pubDate>Wed, 28 Dec 2016 22:46:00 +0000</pubDate>
				<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[amazon]]></category>
		<category><![CDATA[apigateway]]></category>
		<category><![CDATA[aws]]></category>
		<category><![CDATA[ec2]]></category>
		<category><![CDATA[infrastructure]]></category>
		<category><![CDATA[lambda]]></category>
		<category><![CDATA[microservices]]></category>
		<category><![CDATA[s3]]></category>
		<category><![CDATA[servers]]></category>
		<guid isPermaLink="false">http://jessewarden.com/?p=5254</guid>

					<description><![CDATA[Introduction At the beginning of October, I started a new project to help my team move a 12 year old application to the cloud. I knew next to nothing about Amazon, or their infrastructure offerings called AWS. In the past 3 months I&#8217;ve learned a ton. Today I wanted to share what I&#8217;ve learned about [&#8230;]]]></description>
										<content:encoded><![CDATA[<h1>Introduction</h1>
<p>At the beginning of October, I started a new project to help my team move a 12 year old application to the cloud. I knew next to nothing about Amazon, or their infrastructure offerings called AWS. In the past 3 months I&#8217;ve learned a ton. Today I wanted to share what I&#8217;ve learned about Lambdas: Functions you run in AWS.</p>
<p>Also known as serverless architecture.<br />
<span id="more-5254"></span></p>
<h1>What is AWS?</h1>
<p>AWS is short for Amazon Web Services. Amazon provides you a bunch of different services that help you build software, almost all of which they host.</p>
<h1>What Are Lambdas?</h1>
<p>Lambdas are one of their offerings that have been out over a year. The selling points of Lambdas are Amazon sets up and maintains the server for you, and you&#8217;re only charged for how long your code actually runs. You upload code and it just works.</p>
<h1>Why Not Use an EC2 Instead?</h1>
<p>An EC2 is Amazon&#8217;s virtual machine servers. You have to build and maintain them yourself. You pay to keep them running even when they aren&#8217;t handling any traffic. You have to rebuild them when new AMI&#8217;s (virtual machine templates) come out from Amazon. Things get really challenging when you scale dynamically for spikes in traffic.</p>
<h2></h2>
<h1>Why Not Docker?</h1>
<p>While <a href="https://www.docker.com/">Docker</a> makes some of the above less painful, especially when testing in Jenkins or testing on other developers machines, you still have all the same issues. You build the docker image and manage them through a container service like DockerSwarm or <a href="https://www.consul.io/">Consul</a>. The images themselves have to be managed by someone in DockYard.</p>
<h1>Why Lambdas</h1>
<h2>I&#8217;m A Front-End Developer</h2>
<p>If I want to run my JavaScript in the cloud, I don&#8217;t care about the OS, what&#8217;s installed on it, and all the details about keeping it running and refreshed with security updates. Amazon does and handles all that for you.</p>
<p>Lamba&#8217;s are just code, you don&#8217;t have to maintain the server or infrastructure, you only pay for what you use, and they automatically scale based on traffic.</p>
<p>If you&#8217;re a front-end developer like me who just wants to write code, and you&#8217;re keen on building <a href="http://samnewman.io/patterns/architectural/bff/">a back-end API for the front end</a>, they&#8217;re perfect.</p>
<h2>Lambdas Are Reactive and Event Driven</h2>
<p>One additional feature of Lambdas is their built in events. They are &#8220;reactive&#8221; by default. It&#8217;s assumed Lambdas are triggered by other AWS things. Things in this case being API Gateway for REST API&#8217;s such as GET and POST, S3 when you drop files on it, SNS for a basic message bus, or even JSON written into logs through CloudWatch. There also are the building blocks for distributed architecture in Step Functions.</p>
<h2>Simpler Continuous Deployment</h2>
<p>Trying to get monoliths, big applications where all the code is bundled together, deployed to production is hard. Getting this done often is even harder. One of the benefits microservices give you is easier deployment. You can deploy &#8220;one thing&#8221; without having to worry about the &#8220;other things&#8221;.</p>
<p>Anyone who&#8217;s had back-end developers deploy new API&#8217;s, or you deploying new front end code knows that&#8217;s a loaded statement. Unless you&#8217;ve done some integration and functional testing or you&#8217;ve deployed the code to a QA or staging environment which mimics production, you don&#8217;t &#8220;know&#8221; the code works.</p>
<p>If you define clear API&#8217;s upfront, keep the microservices truly simple in their functionality, this process becomes much simpler, and eases CI down the line.</p>
<h1>Are Lambdas Microservices?</h1>
<p>They can be <a href="http://www.martinfowler.com/articles/microservices.html">microservices</a>, but no, not by default. They are just a function. Microservices typically are accessed by a REST API. If you trigger them by an API Gateway (a restful URL provided by Amazon), then yes, they become microservices.</p>
<h1>Build A Microservice</h1>
<p>If you want to build a RESTful microservice with Lambda&#8217;s, you first have to have an AWS account. Assuming you have that, login and access the console (the AWS web interface).</p>
<h2>Step 1: Build A HelloWorld Lambda</h2>
<p>Click the &#8220;Services&#8221; button/menu, and select/search for &#8220;Lambda&#8221;, then click &#8220;Create a Lambda Function&#8221;.</p>
<p><img fetchpriority="high" decoding="async" class="alignnone size-full wp-image-5257" src="http://jessewarden.com/wp-content/uploads/2016/12/Screen-Shot-2016-12-28-at-4.56.30-PM.png" alt="" width="1310" height="456" srcset="https://jessewarden.com/wp-content/uploads/2016/12/Screen-Shot-2016-12-28-at-4.56.30-PM.png 1310w, https://jessewarden.com/wp-content/uploads/2016/12/Screen-Shot-2016-12-28-at-4.56.30-PM-300x104.png 300w, https://jessewarden.com/wp-content/uploads/2016/12/Screen-Shot-2016-12-28-at-4.56.30-PM-768x267.png 768w, https://jessewarden.com/wp-content/uploads/2016/12/Screen-Shot-2016-12-28-at-4.56.30-PM-1024x356.png 1024w" sizes="(max-width: 1310px) 100vw, 1310px" /></p>
<p>In Runtime select &#8220;Node&#8221;; version doesn&#8217;t matter, just ensure not Edge for now. For template, click on &#8220;Blank Function&#8221;.</p>
<p><img decoding="async" class="alignnone wp-image-5258 size-full" src="http://jessewarden.com/wp-content/uploads/2016/12/Screen-Shot-2016-12-28-at-4.57.26-PM-e1482962313250.png" width="310" height="342" /></p>
<h2>Step 2: Choose A Trigger</h2>
<p>Click the empty box and choose &#8220;API Gateway&#8221;. Make up an API Name, choose &#8220;api&#8221; for deployment stage, and choose &#8220;Open&#8221; for security. Click &#8220;Next&#8221;.</p>
<p><img decoding="async" class="alignnone size-full wp-image-5259" src="http://jessewarden.com/wp-content/uploads/2016/12/Screen-Shot-2016-12-28-at-4.59.06-PM.png" alt="" width="1850" height="596" srcset="https://jessewarden.com/wp-content/uploads/2016/12/Screen-Shot-2016-12-28-at-4.59.06-PM.png 1850w, https://jessewarden.com/wp-content/uploads/2016/12/Screen-Shot-2016-12-28-at-4.59.06-PM-300x97.png 300w, https://jessewarden.com/wp-content/uploads/2016/12/Screen-Shot-2016-12-28-at-4.59.06-PM-768x247.png 768w, https://jessewarden.com/wp-content/uploads/2016/12/Screen-Shot-2016-12-28-at-4.59.06-PM-1024x330.png 1024w" sizes="(max-width: 1850px) 100vw, 1850px" /></p>
<h2>Step 3: Configure</h2>
<p>Pick a camel case (ex: likeThisMan) name. Scroll down to Role, and choose &#8220;Create a new role from template(s)&#8221;. Create a basic camel case role name such as &#8220;myCustomTemplateRole&#8221;. Scroll to the bottom and click &#8220;Next&#8221;, then on the next screen scroll to the bottom and click &#8220;Create function&#8221;.</p>
<p><img loading="lazy" decoding="async" class="alignnone size-full wp-image-5260" src="http://jessewarden.com/wp-content/uploads/2016/12/Screen-Shot-2016-12-28-at-5.01.24-PM.png" alt="" width="1824" height="666" srcset="https://jessewarden.com/wp-content/uploads/2016/12/Screen-Shot-2016-12-28-at-5.01.24-PM.png 1824w, https://jessewarden.com/wp-content/uploads/2016/12/Screen-Shot-2016-12-28-at-5.01.24-PM-300x110.png 300w, https://jessewarden.com/wp-content/uploads/2016/12/Screen-Shot-2016-12-28-at-5.01.24-PM-768x280.png 768w, https://jessewarden.com/wp-content/uploads/2016/12/Screen-Shot-2016-12-28-at-5.01.24-PM-1024x374.png 1024w" sizes="auto, (max-width: 1824px) 100vw, 1824px" /></p>
<p>You&#8217;re done!</p>
<p>Note it usually dumps you on the Trigger tab (what causes your Lambda function to run). In our case, it should show the URL for our API Gateway. Copy this to your clipboard or a notepad/textedit for later use.</p>
<p><img loading="lazy" decoding="async" class="alignnone size-full wp-image-5261" src="http://jessewarden.com/wp-content/uploads/2016/12/Screen-Shot-2016-12-28-at-5.02.29-PM.png" alt="" width="2464" height="802" srcset="https://jessewarden.com/wp-content/uploads/2016/12/Screen-Shot-2016-12-28-at-5.02.29-PM.png 2464w, https://jessewarden.com/wp-content/uploads/2016/12/Screen-Shot-2016-12-28-at-5.02.29-PM-300x98.png 300w, https://jessewarden.com/wp-content/uploads/2016/12/Screen-Shot-2016-12-28-at-5.02.29-PM-768x250.png 768w, https://jessewarden.com/wp-content/uploads/2016/12/Screen-Shot-2016-12-28-at-5.02.29-PM-1024x333.png 1024w" sizes="auto, (max-width: 2464px) 100vw, 2464px" /></p>
<p>It generates a basic function for you. You can see it by clicking the Code tab:</p>
<pre><code>exports.handler = (event, context, callback) => {
    callback(null, 'Hello from Lambda');
};</code></pre>
<p>&nbsp;</p>
<h1>Test &amp; Iterate On Your Microservice</h1>
<h2>Step 4: Test</h2>
<p>Click the blue &#8220;Test&#8221; button. In the new popup, the sample event template should be &#8220;Hello World&#8221;. Click &#8220;Save and Test&#8221;, and you should see &#8220;Hello from Lambda&#8221; below the execution result. Great, your Lambda function runs.</p>
<p><img loading="lazy" decoding="async" class="alignnone size-full wp-image-5262" src="http://jessewarden.com/wp-content/uploads/2016/12/Screen-Shot-2016-12-28-at-5.04.29-PM-e1482962708312.png" alt="" width="363" height="141" /></p>
<h2>Step 5: Test Your API Gateway</h2>
<p>If you copy and paste your API Gateway URL in the browser, it should say &#8220;internal server error&#8221;. This is because that Lambda creation wizard you ran created a new REST API for you, but returns a JavaScript string. By default, you need to use JSON. Let&#8217;s modify your Lambda code to do that.</p>
<pre><code>exports.handler = (event, context, callback) =&gt; {
    
    const response = {
        statusCode: '200',
        body: JSON.stringify('Hello from Lambda'),
        headers: {
            'Content-Type': 'application/json',
        },
    }
    callback(null, response);
};</code></pre>
<p>Now re-open the API Gateway URL in your browser, and you should see your &#8220;Hello from Lambda&#8221; message.</p>
<h1>Debug Your Microservice</h1>
<h2>Step 6: Custom Logging</h2>
<p>The event and context parameters allow you to pass dynamic information to your Lambda, and let you know how your Lambda was invoked. Add 2 log statements to show the event and context variables:</p>
<pre><code>exports.handler = (event, context, callback) =&gt; {
    console.log("event:", event);
    console.log("context:", context);</code></pre>
<p>Now click &#8220;Save and Test&#8221;. The log output at the bottom right should show your 2 log messages. The event is probably the custom Hello World default test data of key1, value1, etc.</p>
<p><img loading="lazy" decoding="async" class="alignnone size-full wp-image-5263" src="http://jessewarden.com/wp-content/uploads/2016/12/Screen-Shot-2016-12-28-at-5.05.52-PM.png" alt="" width="1616" height="624" srcset="https://jessewarden.com/wp-content/uploads/2016/12/Screen-Shot-2016-12-28-at-5.05.52-PM.png 1616w, https://jessewarden.com/wp-content/uploads/2016/12/Screen-Shot-2016-12-28-at-5.05.52-PM-300x116.png 300w, https://jessewarden.com/wp-content/uploads/2016/12/Screen-Shot-2016-12-28-at-5.05.52-PM-768x297.png 768w, https://jessewarden.com/wp-content/uploads/2016/12/Screen-Shot-2016-12-28-at-5.05.52-PM-1024x395.png 1024w" sizes="auto, (max-width: 1616px) 100vw, 1616px" /></p>
<p>Think of &#8220;event&#8221; as parameters your Lambda can choose to parse and use to dynamically act on. The context gives your Lambda information about itself while running (log group name, how long your lambda function has to run, etc). Let&#8217;s see how the event can differ.</p>
<h2>Step 7: CloudWatch Logs</h2>
<p>Click the &#8220;Monitoring&#8221; tab, and to the far right you should see &#8220;View logs in CloudWatch&#8221;. Click it.</p>
<p><img loading="lazy" decoding="async" class="alignnone size-full wp-image-5264" src="http://jessewarden.com/wp-content/uploads/2016/12/Screen-Shot-2016-12-28-at-5.06.40-PM.png" alt="" width="2434" height="358" srcset="https://jessewarden.com/wp-content/uploads/2016/12/Screen-Shot-2016-12-28-at-5.06.40-PM.png 2434w, https://jessewarden.com/wp-content/uploads/2016/12/Screen-Shot-2016-12-28-at-5.06.40-PM-300x44.png 300w, https://jessewarden.com/wp-content/uploads/2016/12/Screen-Shot-2016-12-28-at-5.06.40-PM-768x113.png 768w, https://jessewarden.com/wp-content/uploads/2016/12/Screen-Shot-2016-12-28-at-5.06.40-PM-1024x151.png 1024w" sizes="auto, (max-width: 2434px) 100vw, 2434px" /></p>
<p>Hopefully you should see at least 1 log, but probably more.</p>
<p><img loading="lazy" decoding="async" class="alignnone size-full wp-image-5265" src="http://jessewarden.com/wp-content/uploads/2016/12/Screen-Shot-2016-12-28-at-5.07.13-PM.png" alt="" width="1840" height="474" srcset="https://jessewarden.com/wp-content/uploads/2016/12/Screen-Shot-2016-12-28-at-5.07.13-PM.png 1840w, https://jessewarden.com/wp-content/uploads/2016/12/Screen-Shot-2016-12-28-at-5.07.13-PM-300x77.png 300w, https://jessewarden.com/wp-content/uploads/2016/12/Screen-Shot-2016-12-28-at-5.07.13-PM-768x198.png 768w, https://jessewarden.com/wp-content/uploads/2016/12/Screen-Shot-2016-12-28-at-5.07.13-PM-1024x264.png 1024w" sizes="auto, (max-width: 1840px) 100vw, 1840px" /></p>
<p>They are sorted by most recent, so click on the top one. These should match what&#8217;s in your log output when you tested it.</p>
<p>Click the back button, select all the log streams by clicking the box to their left, and click &#8220;Delete Log Stream&#8221; then &#8220;Yes Delete&#8221;.</p>
<p>Reopen the API Gateway URL, then go back to your CloudWatch logs and click the little refresh button (the spinning circle arrows) on the top right. It should have just 1 log which you just caused by re-running your API Gateway URL. Click it, and you&#8217;ll notice the data is much different.</p>
<p><img loading="lazy" decoding="async" class="alignnone size-full wp-image-5266" src="http://jessewarden.com/wp-content/uploads/2016/12/Screen-Shot-2016-12-28-at-5.15.00-PM.png" alt="" width="2428" height="828" srcset="https://jessewarden.com/wp-content/uploads/2016/12/Screen-Shot-2016-12-28-at-5.15.00-PM.png 2428w, https://jessewarden.com/wp-content/uploads/2016/12/Screen-Shot-2016-12-28-at-5.15.00-PM-300x102.png 300w, https://jessewarden.com/wp-content/uploads/2016/12/Screen-Shot-2016-12-28-at-5.15.00-PM-768x262.png 768w, https://jessewarden.com/wp-content/uploads/2016/12/Screen-Shot-2016-12-28-at-5.15.00-PM-1024x349.png 1024w" sizes="auto, (max-width: 2428px) 100vw, 2428px" /></p>
<p>CloudWatch is pretty good at parsing arbitrary strings and JSON. Click the event area in the list, and it should expand it to show you the full JSON. Notice API Gateway sends us a lot of parameters.</p>
<h1>What Languages Can I Use?</h1>
<p>You can write your Lambdas in JavaScript, Python, Java, and C#. You can also use your normal libraries. The tutorial above edits the code inline in the AWS console, but a future tutorial shows you how you can automate your code.</p>
<h1>What Else Can Lambdas Do?</h1>
<p>Amazon&#8217;s documentation gives you <a href="http://docs.aws.amazon.com/lambda/latest/dg/invoking-lambda-function.html#intro-core-components-event-sources">a list of events</a> that can trigger your lambda. However, some real world use cases I&#8217;ve used are:</p>
<h2>REST API&#8217;s</h2>
<p>API Gateway for basic REST Services instead of using Node + <a href="http://restify.com/">Restify</a> + Docker + DockerSwarm (You can still use Node + Restify, heh)</p>
<h2>Backend For Front End</h2>
<p>Database guy had 1 Lambda for his <a href="https://aws.amazon.com/dynamodb/">DynamoDB</a> access. My Lambda was an API for my front-end, and took his JSON and formatted it the way I needed it (my microservice<a href="http://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/Lambda.html#invoke-property"> invoked</a> his microservice).</p>
<h2>Unexpected Spikes In Traffic == No Worries</h2>
<p>Trying to sell a client on how Lambda&#8217;s scaled better, and were cheaper than a dozen WebSphere instances in a row. We wired up <a href="http://gatling.io/#/">Gatling</a> to blast it with hundreds of thousands of users over 2 minutes. Amazon was like, &#8220;That&#8217;ll be $10 please.&#8221; lol! #awesome (This as opposed to the Terminator 2 nuke scene that typically resulted in a spike of traffic with the servers melting).</p>
<h2>Content Mangement Updating Servers</h2>
<p>Dropping updated content from a Content Management System on S3 (a hard drive in the cloud). Then, updating content on some EC2 instances behind an ELB. Using the SDK to <a href="http://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/EC2.html#describeInstances-property">describe instances</a> (what servers do I have, and of those, are they running or not), you can then snag their IP addresses. Our EC2&#8217;s were in a different security group, so we put a lambda in the same group, gave it a URL from API Gateway, then had Lambda A call Lambda B with the IP addresses to call &amp; updated content to give them.</p>
<h1>Conclusions</h1>
<p>As you can see, Lambdas provide a wonderful way to build microservices for both your application, and your infrastructure. You can start with a <a href="http://martinfowler.com/bliki/MonolithFirst.html">monolith first</a> and make your Lambda&#8217;s 1 function turn into a ton, or build a bunch of little ones that may or may not know about each other, but all have a well defined API contract.</p>
<p>Not worrying about servers has freed up me and others to no longer worry about infrastructure, and instead write code.</p>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>Functional Programming for OOP Developers: Part 1</title>
		<link>https://jessewarden.com/2016/08/beginners-guide-to-functional-programming-part-1.html</link>
					<comments>https://jessewarden.com/2016/08/beginners-guide-to-functional-programming-part-1.html#comments</comments>
		
		<dc:creator><![CDATA[JesterXL]]></dc:creator>
		<pubDate>Mon, 29 Aug 2016 01:04:20 +0000</pubDate>
				<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[array]]></category>
		<category><![CDATA[functionalprogramming]]></category>
		<category><![CDATA[higherorder]]></category>
		<category><![CDATA[lambda]]></category>
		<category><![CDATA[listcomprehension]]></category>
		<category><![CDATA[mutation]]></category>
		<category><![CDATA[purefunction]]></category>
		<guid isPermaLink="false">http://jessewarden.com/?p=5160</guid>

					<description><![CDATA[Yeah yeah yeah, tl;dr; and show me the code, yo! Introduction I have been learning Functional Programming over the past year with a friend of mine. We&#8217;ve both cut our teeth on finding who to learn from, what articles are useful, and what actually translates into your day to day programming job. I&#8217;ve also learned [&#8230;]]]></description>
										<content:encoded><![CDATA[<p>Yeah yeah yeah, tl;dr; and <a href="http://jessewarden.com/2016/08/beginners-guide-to-functional-programming-part-1.html#buildingthepredicatereversepyramid">show me the code, yo!</a></p>
<p><a name="introduction"></a></p>
<h1>Introduction</h1>
<p>I have been learning Functional Programming over the past year with a <a href="https://twitter.com/stevensacks">friend of mine</a>. We&#8217;ve both cut our teeth on finding who to learn from, what articles are useful, and what actually translates into your day to day programming job. I&#8217;ve also learned a lot of natural problems that arise as you start a new project from scratch with an <a href="https://en.wikipedia.org/wiki/Object-oriented_programming">OOP</a> background, or if you&#8217;re refactoring some OOP code to be more functional.</p>
<p>In this article, I wanted to share some of what I learned. Specifically what functional programming is, why it matters, how to use pure functions and list comprehensions in the real world. While I use JavaScript in this article, I&#8217;ve learned that the concepts and libraries supporting it are available in many programming languages.</p>
<p><span id="more-5160"></span></p>
<h1>Contents</h1>
<ul>
<li><a href="#whyevenbother">Why Even Bother?</a>
<ul>
<li><a href="#whynot">Why Not?</a></li>
<li><a href="#jobmarket">Job Market</a></li>
<li><a href="#timeandcognitiveload">Time &amp; Cognitive Load</a></li>
<li><a href="#thegoodnews">The Good News</a></li>
<li><a href="#thebadnews">The Bad News</a></li>
<li><a href="#bewareprofessorsandtheelite">Beware Professors &amp; The Elite</a></li>
<li><a href="#isthisforappsorforgamesorboth">Is This For Apps or For Games or Both?</a></li>
<li><a href="#quickglossaryofterms">Quick Glossary of Terms</a></li>
</ul>
</li>
<li><a href="#whatisfunctionalprogramming">What is Functional Programming?</a></li>
<li><a href="#whyisfunctionalprogrammingthisway">Why is Functional Programming This Way?</a></li>
<li><a href="#purefunctions">Pure Functions</a>
<ul>
<li><a href="#academicpurefunctions">Academic Pure Functions</a></li>
<li><a href="#realworldpurefunctions">Real World Pure Functions</a></li>
</ul>
<ul>
<li><a href="#predicates">Predicates</a></li>
<li><a href="#nodepredicates">Node Predicates</a></li>
<li><a href="#buildingthepredicatereversepyramid">Building The Predicate Reverse Pyramid</a></li>
</ul>
</li>
<li><a href="#arraycomprehensions">Array Comprehensions</a>
<ul>
<li><a href="#humbleforeach">Humble For Each</a></li>
<li><a href="#every">Every</a></li>
<li><a href="#some">Some</a></li>
<li><a href="#filter">Filter</a></li>
<li><a href="#reduce">Reduce</a></li>
<li><a href="#combingingcomprehensions">Combining Comprehensions</a></li>
</ul>
</li>
<li><a href="#checkers">Checkers</a></li>
<li><a href="#conclusions">Conclusions</a></li>
<li><a href="#additionalresources">Additional Resources</a></li>
<li><a href="#specialthanks">Special Thanks</a></li>
</ul>
<p><a name="whyevenbother"></a></p>
<h1>Why Even Bother?</h1>
<p>Here&#8217;s my list derived AFTER actually doing it vs. rehashing marketing I&#8217;ve read elsewhere.</p>
<ol>
<li>Code works more than it doesn&#8217;t.</li>
<li>Unit tests are smaller, and easier to write. Smaller mocks, little to no setup/teardown for test suites.</li>
<li>Unit tests break faster allowing me to fix broken code they found faster.</li>
<li>Easier to figure out what the hell is going on in a larger code base. If something breaks, it&#8217;s easier to pull things apart and improve the testing of those parts to prevent it from happening again. Not like usual spaghetti that can occur with mutable state. Caveat is hard to reason what&#8217;s happening in deeply composed predicates; still learning how to debug this.</li>
</ol>
<p>I&#8217;ll elucidate more on those topics below.<br />
<a name="whynot"></a></p>
<h1>Why Not?</h1>
<p><a name="jobmarket"></a></p>
<h2>Job Market</h2>
<p>The echo chamber, albeit a large one, that is JavaScript community (both Node and web) would have you believe the world is moving Functional, and that if you&#8217;re using OOP, you clearly missed <a href="https://medium.com/@cscalfani/goodbye-object-oriented-programming-a59cda4c0e53#.bops2quxi">the memo</a>. Facebook started it with <a href="https://facebook.github.io/immutable-js/">Immutable.js</a>, <a href="https://facebook.github.io/flux/">Flux</a>, and <a href="https://github.com/reactjs/redux">Redux</a>, and Google, Mozilla, &amp; crew have followed suit by nuking <a href="https://mail.mozilla.org/pipermail/es-discuss/2015-November/044684.html">Object.observe</a>, and Google slowly morphing <a href="https://angular.io/">Angular 2</a>&#8216;s development to adopt these newer ideas of <a href="https://vsavkin.com/two-phases-of-angular-2-applications-fda2517604be#.x08g50d2m">unidirectional data flow</a>, Observables, <a href="https://hashnode.com/post/why-does-react-emphasize-on-unidirectional-data-flow-and-flux-architecture-ciibz8ej600n2j3xtxgc0n1f0">etc</a>. Netflix, too, has made huge strides by rewriting much of their site in <a href="https://github.com/Reactive-Extensions/RxJS">RxJS</a>, and helping promote the <a href="http://www.reactivemanifesto.org/">Reactive Manifesto</a> as &#8220;the new way&#8221; to build applications, both client and server (yes, it&#8217;s 2 pages, and no, you won&#8217;t walk away knowing how to build reactive applications after reading it). <a href="https://msdn.microsoft.com/en-us/visualfsharpdocs/conceptual/visual-fsharp">Microsoft&#8217;s F#</a> push has added more fuel.</p>
<p>I can tell you from consulting experience and my new job that OOP, mutable state, and languages that support them are alive and well.<br />
<a name="timeandcognitiveload"></a></p>
<h2>Time &amp; Cognitive Load</h2>
<p>The other 2 reasons are it takes longer to make things mathematically correct, and as you learn, you often refactor functions a lot to make them more pure. While that&#8217;s great, you bubble up the variables storage and creation to a higher level. Over time this results in you eventually having to store/get that data from somewhere. Frameworks like <a href="http://redux.js.org/">Redux</a> help here, but it&#8217;s takes more time to make things nice and pure. While the cognitive load (keeping how the program works in your head as you read the code) actually lowers with pure functions, assembling &amp; testing them can take a lot out of you once you start dealing with higher order functions and work out how to test the larger functions. This is assuming you&#8217;re doing tests in tandem with your code.</p>
<h2>It&#8217;s New</h2>
<p>If it&#8217;s new, you don&#8217;t have an inborn talent for functional programming, nor a penchant for <a href="https://en.wikipedia.org/wiki/Lambda_calculus">Lambda Calculus</a>,  then it&#8217;ll be hard at first. Like unit testing, deadlifting, or doing a hand stand, you have to practice. This takes time. It can reduce the accuracy of time estimates. You&#8217;ll get frustrated as you try, fail, repeat.</p>
<p><a name="thegoodnews"></a></p>
<h1>The Good News</h1>
<p>Typically I start these articles with the bad news first, but given the scope of the endeavor we&#8217;re about to embark upon, I feel it necessary to start positive.</p>
<p>You most likely already know a lot of this already.</p>
<p>Additionally, there is less overhead in applying these techniques into existing code bases. You can pull in functional techniques (and you probably already have) while still staying true to an existing code base&#8217;s OOP bent, nor with adversely affecting anything. Some is language agnostic.</p>
<p>This stuff is easier to grok than a lot of these academics and 300 IQ programmers make it out to be. I&#8217;m an art student learning it with good old hard work, which means so can you. Like anything, it just takes practice.</p>
<p>You don&#8217;t need to know <a href="https://www.haskell.org/">Haskell</a>, <a href="https://clojure.org/">Clojure</a>, or <a href="http://www.scala-lang.org/">Scala</a>.<br />
<a name="thebadnews"></a></p>
<h1>The Bad News</h1>
<p>You&#8217;ll have to wade through a lot of Google search results to find blog posts, even StackOverflow answers, written in easy to understand english. A good many, well meaning academics write these posts using proper terminology, but you leave not knowing how any of it relates to your day to day job and how these techniques can help your daily problems. Smart programmers have taken it upon themselves to give code examples that help you understand how to write functional code, but you&#8217;d never actually need a function that adds 1 to 10 in the real world.</p>
<p>If you grew up in OOP like me, it&#8217;s hard to break a decade or more of habits you&#8217;ve ingrained in your brain. Worse, you&#8217;ll have patterns and ways of thinking that shape how you approach solving programming problems.</p>
<p>The industry as a whole, at least for web front end (and some Node) is built around mutability and state. Reading text files, databases, encapsulation with classes, and other state full things have copious tutorials and StackOverflow answers with state. Because it&#8217;s easy. Because it&#8217;s quick. Because it works.</p>
<p>Simplification of many functional programming terms also poses a challenge because some people think you either cheapen it by doing so, incorrectly explain it by not using all the appropriate terms, or are flat out wrong by pointing out the core value. Ignore it, there are diamonds inside, you just have to ignore all the yuck that goes with mining. Think <a href="https://minecraft.net/en/">Minecraft</a>: no grime, just your time.<br />
<a name="bewareprofessorsandtheelite"></a></p>
<h1>Beware Professors &amp; The Elite</h1>
<p>It&#8217;s worth re-iterating: beware academics and elitists. Functional Programming can be for the masses, not some secret cult. Additionally, you can use pieces and get the benefit; you do not need to go full bore to realize positive results in your code and day job.</p>
<p>Try it in pieces. You won&#8217;t hurt yourself, nor destroy your codebase. If you offend some PHD, oh well, the world goes on.<br />
<a name="isthisforappsorforgamesorboth"></a></p>
<h1>Is This for Apps or for Games or Both?</h1>
<p>I&#8217;ve done no active research for functional programming in games, but did see that <a href="http://debug.elm-lang.org/edit/Mario.elm">Elm Repeatable Mario demo</a>. Using the <a href="http://t-machine.org/index.php/2007/09/03/entity-systems-are-the-future-of-mmog-development-part-1/">Component Entity System</a> model, I&#8217;ve been having fun <a href="https://github.com/JesterXL/Final-Fantasy-All-The-Bravest-in-Redux">trying make a mash up</a> of <a href="https://www.youtube.com/watch?v=gLk61_4N_fY">Final Fantasy 6</a> &amp; <a href="https://www.youtube.com/watch?v=5mYd12L4iE4">Final Fantasy All The Bravest</a>.</p>
<p><iframe loading="lazy" src="https://www.youtube.com/embed/FQQhUj4l_3g" width="560" height="315" frameborder="0" allowfullscreen="allowfullscreen"></iframe><br />
<a name="quickglossaryofterms"></a></p>
<h1>Quick Glossary of Terms</h1>
<p><strong>Mutable</strong>: You can set a variable again and again. Opposite of a constant. Mutable state means I can set the variable to something else later.</p>
<pre><code>var age = 37;
// cool
age = 38;</code></pre>
<pre><code>const age = 37;
// "TypeError: Assignment to constant variable.
age = 38;</code></pre>
<p><strong>Side Effect</strong>: When you call a function and it modifies a variable outside it&#8217;s scope.</p>
<pre><code>var age = 37;
var birthday = () =&gt; age++;</code></pre>
<p>Specifically, you modify variables outside the function. If it wasn&#8217;t a parameter passed in, or it&#8217;s not within the function closure, it&#8217;s outside, so you should not touch it.</p>
<pre><code>var birthday = (age) =&gt; age + 1;</code></pre>
<p><strong>Imperative</strong>: Programming languages where you describe how to do something, use a lot of mutable state, and are typically associated with non-functional programming.</p>
<p><strong>Higher Order Function</strong>: When you pass a function to another function. JQuery&#8217;s click, event handlers, etc. are examples:</p>
<pre><code>// notice first and only parameter passed to click
$( "#target" ).click(function() {
  alert( "Handler for .click() called." );
});</code></pre>
<p><a name="whatisfunctionalprogramming"></a></p>
<h1>What Is Functional Programming?</h1>
<p>The simple definition of Functional Programming is writing functions like you&#8217;d write Algebra and instead of changing data, you get new data.</p>
<p>You write <a href="https://medium.com/javascript-scene/master-the-javascript-interview-what-is-a-pure-function-d1c076bec976#.ajnf9zpzs">pure functions</a> and try to ensure your data is <a href="https://en.wikipedia.org/wiki/Immutable_object">immutable</a> <strong>as possible</strong>.<br />
<a name="whyisfunctionalprogrammingthisway"></a></p>
<h1>Why is Functional Programming this way?</h1>
<p>Predicability.</p>
<p>In math, if I add 1 + 1, I know that the answer is always 2. That&#8217;s predictable. If I grabbed a random function from anywhere in your code base, and called it twice with the same parameters, would it return the same result each time? Exactly.</p>
<p>In Algebra, you &#8220;solve for x&#8221;. In math, they&#8217;ll say x = 1 + 2. If you&#8217;ve done Algebra, you know x is equal to 3. In code, it&#8217;d be:</p>
<pre><code>function getX()
{
   return 1 + 2;
}</code></pre>
<p>The important thing here, which may seem painfully obvious, is if you call getX(), you&#8217;ll always get 3 back.</p>
<p>If you&#8217;ve done any non-functional programming, you know that&#8217;s NOT always the case. Observe.</p>
<pre><code>function getX()
{
   return 1 + 2 + data;
}</code></pre>
<p>What is X now? No clue. If someone sets data to 0, then it&#8217;s 3. If someone sets data to &#8216;0&#8217;, then it&#8217;s &#8217;30&#8217;. That, my friends, is not Algebra. You can no longer &#8220;mathematically prove&#8221; getX returns 3. You have to know the history of what happened before, or even while, you call getX.</p>
<p>Lastly? No errors. If your functions are truly pure, you don&#8217;t get thrown exceptions. You only need try/catch for particular nasty/scary sections of your code, 3rd party code, or known mutable sections like database calls or text file read/writes, or just gnarly data parsing/mangling.</p>
<p>Once you can start depending on functions that don&#8217;t break, you can start to build more resilient and testable applications.<br />
<a name="purefunctions"></a></p>
<h1>Pure Functions</h1>
<p><a name="academicpurefunctions"></a></p>
<h2>Academic Pure Functions</h2>
<p>You do this through pure functions: Functions that always return the same result with certain parameters, no many how many times they are called. You saw above the first getX function had no parameters. Let&#8217;s give it some:</p>
<pre><code>function add2(a, b)
{
   return a + b;
}</code></pre>
<p>Assuming the function is always passed non-decimal numbers, you&#8217;ll always get the same result.</p>
<pre><code>add2(1, 1); // 2
add2(3, 5); // 8
add2(0, 0); // 0</code></pre>
<p>In fact, you can pass in strings, arrays, objects, and even Errors, changing the order of the parameters, and Chrome has improved the pureness of the addition operator, <a href="https://www.destroyallsoftware.com/talks/wat">unlike in the past</a>.<br />
<a name="realworldpurefunctions"></a></p>
<h1>Real World Pure Functions</h1>
<p>Let&#8217;s take a look at the real world. In a Node project I&#8217;ve worked on, there are 2 core problems pure functions have helped me with. Specifically using Predicates and Higher Order Functions. DAT POCKETWATCH, THO.<br />
<a name="predicates"></a></p>
<h3>Predicates</h3>
<p>Predicates are pure functions that always return true or false and are used for 2 things: To assert obvious things, and used as building blocks to make more ambitious, complicated assertions.</p>
<p>While available in any language, and highly sought after in languages with dynamic typing, strong typing can only take you so far. Eventually you&#8217;ll create a domain model, aka &#8220;your version of the world described in code&#8221; that you want to prove. Like proofs and postulates in Geometry, you start small, and work your way up. The stronger your simple predicates, the stronger your composed predicates become. Composed just means more complex functions made from many smaller functions.</p>
<p>Reminder: These are not unit tests. They&#8217;re just functions.<br />
<a name="nodepredicates"></a></p>
<h3>Node Predicates</h3>
<p>In my <a href="https://nodejs.org/en/">Node</a> API&#8217;s, I make assertions about the data you send me for creating a new user. I use predicates to verify the POST variables you send over the wire as JSON are legit. Easy, right? Not in JavaScript. It has <a href="http://stackoverflow.com/questions/332422/how-do-i-get-the-name-of-an-objects-type-in-javascript">no types</a>, nor runtime support for type mis-matching.</p>
<p>Strongly-typed languages still have to deal with parsing unstructured data, and in-memory, already parsed data that they have to make some assertions, NOT assumptions, against. Thus, predicates are still applicable both at runtime as well as in tests.</p>
<p>Let&#8217;s start small with some good news: There are already some wonderful, low-level predicates written for you in a library called <a href="https://lodash.com">Lodash</a>. Others like <a href="http://underscorejs.org/">Underscore</a>, <a href="http://ramdajs.com/0.22.1/docs/">Ramda</a>, and <a href="https://github.com/1-liners/1-liners">1-liners</a> exist as well. This is important, so we don&#8217;t have to deal with the differences between <a href="http://stackoverflow.com/questions/5076944/what-is-the-difference-between-null-and-undefined-in-javascript">null and undefined</a>, <a href="http://stackoverflow.com/questions/359494/which-equals-operator-vs-should-be-used-in-javascript-comparisons">== and ===</a>, nor ever care again.</p>
<p>Here is the REST call&#8217;s signature:</p>
<p><strong>URL</strong>: https://some.server.com/api/user<br />
<strong>Type</strong>: POST<br />
<strong>Body</strong>: Object which has firstName, lastName, EID, adjustmentNumber, activated, creatingEID, and roleID.<br />
<strong>Description</strong>: When you want to create a user, send their name, company ID, who&#8217;s creating this user, what role they are assigned to, whether they are start out activated in the system, and the adjustment number for tracking purposes.<br />
<a name="buildingthepredicatereversepyramid"></a></p>
<h3>Building the Predicate Reverse Pyramid</h3>
<p>Let&#8217;s start small and work our way up. Lodash will give us the firm foundation. Strong-typing people, bear with me as we work our way up to higher level predicates.</p>
<p>In Node, your client requests come in this object called Request, whether you&#8217;re using <a href="http://expressjs.com/en/api.html#req">Express</a> or <a href="http://restify.com/#request-api">Restify</a>. For PUT and POSTS, it should have a body object that has all the JSON the client sent us.</p>
<p>&#8230; wait, &#8220;should&#8221;? No no, strong people, strong, MUST! MUST OR <a href="https://www.youtube.com/watch?v=GKNX6dieVcc">AND DEN</a> OR <a href="https://www.youtube.com/watch?v=32kN5r-YZFY">U SHALL NOT PASS</a>!</p>
<p>Notice, in JavaScript, a null or undefined request is still a worthless request. We gotta have strong basics, remember. Lodash has the opposite of what we need, a _.isNil predicate (is something null or undefined). We need the opposite. Let&#8217;s create our own.</p>
<pre><code>var notNil = _.negate(_.isNil);</code></pre>
<p>Cool, let&#8217;s test it. I&#8217;m just using <a href="http://jsbin.com/">JSBin.com</a> to play around, but you can use Node &amp; <a href="https://mochajs.org/">Mocha</a>, <a href="http://jasmine.github.io/">Jasmine</a>, <a href="https://github.com/substack/tape">Tape</a>, or <a href="https://github.com/defunctzombie/commonjs-assert">Assert</a> locally, whatever works for you.</p>
<pre><code>var notNil = _.negate(_.isNil);
console.log(notNil()); // false
console.log(notNil(null)); // false
console.log(notNil(undefined)); // false
console.log(notNil('')); // true
console.log(notNil({})); // true</code></pre>
<p>The first 3 are important. Nothing, which in JavaScript is undefined, we interpret as nil. The 2nd two, being explicit, also are nil. An empty string and an object, the basics of what we get in JSON from clients, are legit. Next up, the body:</p>
<pre><code>var isThereAndHasBody = (req) =&gt; notNil(req) &amp;&amp; notNil(req.body);
// or
function isThereAndHasBody(req)
{
   return notNil(req) &amp;&amp; notNil(req.body);
}</code></pre>
<p>While both functions basically do the same thing, the declared (or named function) is <a href="http://stackoverflow.com/questions/336859/javascript-function-declaration-syntax-var-fn-function-vs-function-fn">hoisted</a>, defined when the outside script is run, and has a this. The last part is the impure part; a function&#8217;s this can change based on who calls it, where, and how using things like <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/bind">bind</a> and Function.<a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/call">call</a>/<a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/apply">apply</a>. As an ex-Flash Developer, I saw this take 6 years to solve. In JavaScript, half <a href="https://johnpapa.net/angularjss-controller-as-and-the-vm-variable/">avoid it entirely</a> whereas others clamor for binds all over the place in ES6 classes.</p>
<p>While your first temptation may be to omit the notNil(req), there are 2 things I want you to note here. First, if we didn&#8217;t place it there, our function would return possibly 3 values: true, false, and an uncaught exception if you passed in a non-object or null/undefined. A predicate returns only true or false, not true, false, and boomz.</p>
<p>Second, notice what the function asserts. That a &#8220;request is actually there, AND has a body&#8221;. That predicate is asserting that it&#8217;s a valid object, and that object exists.</p>
<blockquote><p>&#8220;But why can&#8217;t we just control the order you call the functions, ensure we&#8217;ve already done that check before hand?&#8221;</p></blockquote>
<p>Then the function is no longer pure. Like the getX example way up above, you have to know the history.</p>
<p>There ARE other options, though, like caching the value via <a href="https://lodash.com/docs#memoize">memoize</a>, a safer way to get properties via a safe <a href="https://lodash.com/docs#get">get</a>, or your own controlled predicate via <a href="https://lodash.com/docs#chain">chain</a> or <a href="https://lodash.com/docs#flow">flow</a>.</p>
<p>They&#8217;re hardcore mode, though, so let&#8217;s keep it simple.</p>
<p>Next up, verifying the firstName is legit:</p>
<pre><code>var validName = (o) =&gt; notNil(o) &amp;&amp; _.isString(o);
var requestHasValidFirstName = (req) =&gt; isThereAndHasBody(req) &amp;&amp; validName(req.body.firstName)</code></pre>
<p>We create a validName predicate and then use it plus our previously created isThereAndHasBody predicate together.</p>
<pre><code>console.log(requestHasValidFirstName()); // false
console.log(requestHasValidFirstName({body:{}})); // false
console.log(requestHasValidFirstName({body:{firstName: new Date()}})); // false
console.log(requestHasValidFirstName({body:{firstName: ''}})); // true
console.log(requestHasValidFirstName({body:{firstName: 'Jesse'}})); // true</code></pre>
<p>This is the part where you start to realize, &#8220;I thought predicates were going to be a piece of cake, asserting uber obvious stuff, and yet&#8230; subtle bugs creep in.&#8221; Can you spot it? A firstName of &#8221; is not a valid first name. Let&#8217;s modify our validName to be more stringent.</p>
<pre><code>var validName = (name) =&gt;
{
	return notNil(name) &amp;&amp;
	_.isString(name) &amp;&amp;
	name.length &gt; 0;
};
// ...
console.log(requestHasValidFirstName({body:{firstName: ''}})); // false</code></pre>
<p>Now we&#8217;re talking. Let&#8217;s re-use for the lastName:</p>
<pre><code>var requestHasValidLastName = (req) =&gt; isThereAndHasBody(req) &amp;&amp; validName(req.body.lastName);
console.log(requestHasValidLastName()); // false
console.log(requestHasValidLastName({body:{lastName: ''}})); // false
console.log(requestHasValidLastName({body:{lastName: 'Warden'}})); // true</code></pre>
<p>Much easier, all I had to do was copy pasta the firstName predicate, and change req.body.lastName. Notice at this point you&#8217;ve been composing functions within functions. Your notNil uses Lodash. Your validName uses Lodash + your notNil. Your isThereAndHasBody uses your wrappers over Lodash, etc. You repeat this process to build out the rest of the predicates you need as well as create predicates that assert higher level statements about your data model.</p>
<p>The key point not to miss is that they are ALL pure functions. No matter what order you call, nor what parameters, you&#8217;ll always get the same result. You now have a ton of code that is dependable. (Yes, you should still unit test them).<br />
<a name="arraycomprehensions"></a></p>
<h1>Array Comprehensions</h1>
<p>Now that you have a bunch of predicates, you&#8217;ll want to apply them all at once. Most languages deal with lots of things in a list. In JavaScript, that&#8217;s an Array. <a href="https://en.wikipedia.org/wiki/List_comprehension">List Comprehensions</a> are basically like for loops, except they act like a predicate on an array, items in the array, items in an Object, or both. I&#8217;ll show a few first, then we&#8217;ll use them with our predicates above.<br />
<a name="humbleforeach"></a></p>
<h3>Humble For Each</h3>
<p>If you&#8217;ve done a loop on an array, you often will use the for each:</p>
<pre><code>var list = ["uno", "dos", "tres"];
for(var i=0; i&lt;list.length; i++)
{
   console.log(list[i]);
}</code></pre>
<p>She&#8217;s been one of the core workhorses in my career. Here&#8217;s the functional equivalent:</p>
<pre><code>_.forEach(list, i =&gt; console.log(i));</code></pre>
<p>You&#8217;ll notice most all array comprehension methods follow a similar function signature of the array to operate on, a function to run on each item of the array, and will return something. &#8220;Yo, call this function on each item&#8221;.<br />
<a name="every"></a></p>
<h3>Every</h3>
<p>Going back to our validation predicates, how do we know if they all worked? <a href="https://lodash.com/docs#every">Lodash&#8217; every</a> will loop through all the things. If even one of the callbacks returns false, then every will return false. If all the things return true, then every will return true.</p>
<p>A simple example:</p>
<pre><code>var list = [true, true, true];
var result = _.every(list, function(item)
{
  return item;
});
console.log(result); // true</code></pre>
<p>Or the shorthand version:</p>
<p>var result = _.every(list, i =&gt; i);</p>
<p>All fat arrow functions do an implied return for you. So not this:</p>
<pre><code>_.every(list, i =&gt; return i)</code></pre>
<p>but this:</p>
<pre><code>_.every(list, i =&gt; i)</code></pre>
<p>Cool, now let&#8217;s apply to our validation predicates the same way:</p>
<pre><code>var validRequest = (request) =&gt; _.every([
  isThereAndHasBody,
  hasLegitFirstName,
  hasLegitLastName,
  hasValidEID,
  validAdjrNumNumber,
  validActvIndNumber,
  validCreatingEIDNumber,
  validSSORoleID
], predicate =&gt; predicate(request));</code></pre>
<p>We pass in a request object (in Express/Restify, it&#8217;s an Object which has a params for GET&#8217;s and body for POST&#8217;s, etc). We give it a list of functions which, hopefully, return a true. The last parameter is our callback that takes the predicate, passes the request to it, and returns the result. &#8220;Yo dog, I got this request from node, can you pass it to each of these functions, and if they all say true, lemme know, else, just heck with it, false&#8221;.</p>
<p>Whether we pass empty, an object or even an empty body, she&#8217;ll always report false:</p>
<pre><code>console.log(validRequest()); // false
console.log(validRequest({})); // false
console.log(validRequest({body:{}})); // false</code></pre>
<p>but if we pass the right <a href="https://www.youtube.com/watch?v=uE6Z1nBqLwo">stuff</a>:</p>
<pre><code>console.log(validRequest({
  body: {
    firstName: 'Jesse',
    lastName: 'Warden',
    eid: 'aaa111',
    adjrNum: 1,
    actvInd: 1,
    cretNum: 'aaa111',
    ssoRoleID: 1
  }
})); // true</code></pre>
<p>She&#8217;s good to go. Now we can validate all requests with assurance when they come in. Another thing, these things are cake to unit test. Here&#8217;s some <a href="https://mochajs.org/">Mocha</a> examples:</p>
<pre><code>it('test is a valid name', function()
{
	predicates.validName('test').should.be.true;
});
it('blank is not a valid name', function()
{
	predicates.validName('').should.be.false;
});
it('numbers are not a valid name', function()
{
	predicates.validName(1).should.be.false;
});</code></pre>
<p><a name="some"></a></p>
<h3>Some</h3>
<p>Let&#8217;s cover 3 more so you can refer to them later in the post where we&#8217;ll use them.</p>
<p>In the application I&#8217;m building on at work, we do the same search against multiple databases looking for a match amongst a lot of old data. If even 1 out of the 3 searches finds something, that&#8217;s great! When I get a match from a search, I return it like this:</p>
<pre><code>{
  success: true,
  result: [... the data I found]
}</code></pre>
<p>If I didn&#8217;t find anything, I get:</p>
<pre><code>{
  success: false,
  error: ... reason why it didn't find anything
}</code></pre>
<p>Now, using old sk00l, imperative techniques, I&#8217;d go:</p>
<pre><code>var searchResults = [
  {success: false, error: 'no id matches'},
  {success: false, error: 'no id matches'},
  {success: true, result: [{id: 1, name: 'Cow'}, {id: 1, name: 'Moo'}]}
];
function foundAMatch(searchResults)
{
  var len = searchResults.length;
  for(var i=0; i&lt;len; i++)
  {
    var o = searchResults[i];
    if(o.success)
    {
      return true; 
    }
  }
  return false;
}
console.log(foundAMatch(searchResults)); // true</code></pre>
<p>The new way is to use <a href="https://lodash.com/docs#some">some</a> (sometimes called any):</p>
<pre><code>function foundAMatch(searchResults)
{
  return _.some(searchResults, o =&gt; o.success);
}</code></pre>
<p>If any of the callbacks return true, then some returns true. If all of them return false, then some returns false. Now when I make a bunch of <a href="http://www.html5rocks.com/en/tutorials/es6/promises/">Promise</a> calls, if even 1 of my searches succeeds, I can see if it found a match in a pure way. How do I get it?<br />
<a name="filter"></a></p>
<h3>Filter</h3>
<p>Filter you give an array, and gives you an array back with only the items you want in it. It filters things in and out. Here we can filter some cows:</p>
<pre><code>var animals = [{type: 'cow'}, {type: 'dog'}, {type: 'lizard'}, {type: 'cow'}];
function onlyCowsUpInThisMug(list)
{
  return _.filter(list, function(item)
  {
      if(item.type === 'cow')
      {
          return true;
      }
      else
      {
        return false;
      }
  });
}
console.log(onlyCowsUpInThisMug(animals).length); // 2</code></pre>
<p>Or the more succinct, <a href="http://es6-features.org/#Constants">ES6</a>&#8216;ish way:</p>
<pre><code>var onlyCowsUpInThisMug = (o) =&gt; _.filter(o, o =&gt; o.type === 'cow');</code></pre>
<p>&#8220;Yo, take this list, and take out the things that aren&#8217;t cows, kthxbai.&#8221;</p>
<p>Using our search above, I can get only the successful searches:</p>
<pre><code>var successfulSearches = (searchResults) =&gt; 
_.filter(searchResults, result =&gt; result.success);
console.log(successfulSearches(searchResults).length); // 2</code></pre>
<p><a name="reduce"></a></p>
<h3>Reduce</h3>
<p>Cool, there&#8217;s just one thing left, getting combined list of those searches. However, they&#8217;re all objects of success and result&#8230; I just need the result Array, and I need all of them combined. We&#8217;ll use <a href="https://lodash.com/docs#reduce">reduce</a> to do that.</p>
<p>Reduce is used to take an array, and give you a new one with reduced data. &#8220;Reduced&#8221; is subjective, however. You can reduce an array to whatever you want. You could reduce data, add new data, or return the same thing, up to you. Unlike other list comprehension methods, reduce takes an optional 3 parameter, something called the accumulator, to accumulate, or collect all the results. This is, like most things in Functional programming, an array.</p>
<p>In imperative, you&#8217;d use nested for loops (or some for prop if you take this stupid whiteboard/fizz buzz tests people give you in dumb coding interviews):</p>
<pre><code>var searchResultsThatWorked = successfulSearches(searchResults);
var resultsLen = searchResultsThatWorked.length;
var accumulated = [];
for(var r=0; r&lt;resultsLen; r++)
{
  var searchResultItem = searchResultsThatWorked[r];
  var itemsLen = searchResultItem.result.length;
  for(var i=0; i&lt;itemsLen; i++)
  {
    accumulated.push(searchResultItem.result[i]);
  }
}
console.log(accumulated.length); // 2</code></pre>
<p>Vars everywhere. Let&#8217;s use reduce instead:</p>
<pre><code>var accumulated = _.reduce(searchResultsThatWorked, 
(accumulated, searchResultItem)=&gt;
{
  return accumulated.concat(searchResultItem.result); 
}, []);
console.log(accumulated.length); // 2</code></pre>
<p>You&#8217;ll notice that I stored the results of reduce in the accumulated variable. However, I used an empty array as the 3rd parameter to reduce. While pure, you could set that 3rd parameter to another variable if you wanted to. We just wrap that reduce in a function called reduceAllSearches.</p>
<pre><code>var reduceAllSearches = (searchResults) =&gt; {
  return _.reduce(searchResultsThatWorked, (accumulated, searchResultItem)=&gt;
  {
    return accumulated.concat(searchResultItem.result); 
  }, []);
};</code></pre>
<p>Yes, for the first 2 years it&#8217;s hard to read. With practice, your brain adapts to pick out the callback from the call from the array. I&#8217;m not being sarcastic for a change, I&#8217;m serious. When I first saw this stuff, even before ES6 fat arrow functions, I was like &#8220;What a mess&#8221;. You&#8217;re welcome to use named functions with more clear variable names if that helps your readability. The point here is to use pure functions with arrays via list comprehension methods.<br />
<a name="combingingcomprehensions"></a></p>
<h3>Combining Comprehensions</h3>
<p>Putting it all together:</p>
<pre><code>if(foundAMatch(searchResults))
{
  var foundResults = reduceAllSearches(searchResults);
  // ... send foundResults to client
}</code></pre>
<p><a name="checkers"></a></p>
<h1>Checkers</h1>
<p>There are 3 problems, sadly, with our above carefully crafted predicates.</p>
<ol>
<li>If it returns false, we don&#8217;t know which one failed, nor why.</li>
<li>If we don&#8217;t know, then we can&#8217;t tell the user how to fix their request.</li>
<li>The lack of exceptions in pure functions, which at first you thought was cool, makes it hard to know who failed when they are so deeply composed. (Smartasses will go &#8220;well, perhaps if you unit tested them, you&#8217;d know&#8221;)</li>
</ol>
<p>I&#8217;ll show you how to write checker functions, a trick taught to me by <a href="https://twitter.com/petrillic">Chris Petrilli</a>. Checkers are like predicates, except instead of always returning true or false with no exceptions, they always return an array. If the array is empty, great, no errors. If it has even 1 item in it, it&#8217;s the reason(s) why the predicate failed.</p>
<p>For small checkers, this is obvious stuff, and pointless in strongly typed languages: &#8220;Yo dog, Date&#8217;s aren&#8217;t a String&#8221;. Well duh Cap&#8217;n Obvious, tanks fo nuthin&#8217;. For higher level stuff, and across strongly typed boundaries (HTTP requests, database, parsing data, etc), they are immensely helpful in debugging, both your own code and others. They also take a lot of work, whether you&#8217;re a n00b at functional programmer, or an ace.</p>
<p>Let&#8217;s add some to our above predicates to see how they work. To do that, we need to create these new type of functions easily. In strongly typed languages, you can just create an interface. For dynamic ones, we&#8217;ll take advantage of functions being basically Objects and create special ones by adding data to them we need.</p>
<p>Let&#8217;s create something called a validator. It&#8217;s basically a predicate, but if it returns false, we can inspect it and snag a descriptive error message of it as to why it failed.</p>
<pre><code>var validator = (errorMessage, funk) =&gt;
{
	var predicateWrapper = function()
	{
		return funk.apply(funk, arguments);
	};
	predicateWrapper['errorMessage'] = errorMessage;
	return predicateWrapper;
}</code></pre>
<p>We wrap our predicate, and add the error message to it. Let&#8217;s use with our validName predicate:</p>
<pre><code>var nameValidator = validator('Not a valid name, Holmes.', validName);
console.log("no name:", nameValidator()); // false
console.log("Jesse:", nameValidator('Jesse')); // true</code></pre>
<p>Ok, seems to work exactly like a predicate. But check this out:</p>
<pre><code>console.log(nameValidator.errorMessage); // "Not a valid name, Holmes."</code></pre>
<p>Cool, so if it fails, people can look at that errorMessage to see why. Those of you with OOP deep in yo bones are probably like:</p>
<blockquote><p>Yo, why can&#8217;t we just go validName.errorMessage = &#8220;Not a valid name, Holmes&#8221; and call it a day?</p></blockquote>
<p>That&#8217;s not a Pure Function, brah! But sure, you could. As you use more list comprehensions, you&#8217;ll see your &#8220;default mode in life&#8221; is to start creating functions for everything so you can use them with things that expect functions. That&#8217;s why I created <code>notNil</code> up above instead of using <code>!_.isNil</code>. You can&#8217;t pass !_.isNil to list comprehensions.</p>
<p>You don&#8217;t use validators directly like you use predicates, they are just a function that houses an error message so when they boom, people know why. Those people in this case are the checkers. Let&#8217;s make the function for that:</p>
<pre><code>var checker = function()
{
  var validators = _.toArray(arguments);
  return (thingYouWantToValidate)=&gt;
  {
    return _.reduce(validators, (errors, validatorFunk)=&gt;
                    {
      if (validatorFunk(thingYouWantToValidate))
      {
        return errors;
      }
      else
      {
        return _.chain(errors).push(validatorFunk.errorMessage).value();
      }
    }, []);
  };
};</code></pre>
<p>Whaaa&#8230; ok, in a nutshell please?</p>
<p>&#8220;Yo, I&#8217;m going to send you some predicate functions I made. If you could give me a function back that runs them and gives me an empty array when they work, or errors in that array for the ones that don&#8217;t.&#8221;</p>
<p>We&#8217;ll start with 1, our name validator.</p>
<pre><code>var checkName = checker(nameValidator);
console.log(checkName()); // ["Not a valid name, Holmes."]
console.log(checkName('Jesse')); // []</code></pre>
<p>Make sense, now? Our checker is smart enough to go, &#8220;If this thing returns false, look for that errorMessage&#8221;.</p>
<p>Let&#8217;s do something more sophisticated, and combine our request verifier. Let&#8217;s create 3 new validators, and throw &#8217;em in a checker:</p>
<pre><code>var isThereAndHasBodyValidator = validator('No body or invalid request.', isThereAndHasBody);
var firstNameValidator = validator('Not a valid firstName.', hasLegitFirstName);
var lastNameValidator = validator('Not a valid lastName.', hasLegitLastName);
var checkNameRequest = checker(isThereAndHasBodyValidator, firstNameValidator, lastNameValidator);</code></pre>
<p>The checkNameRequest will first verify it&#8217;s an object with a body, then verify both the first and last name are valid. For the ones that fail, it&#8217;ll put the errorMessages in the array, and when all done, send that array back. Full of errors for invalid, empty for valid:</p>
<pre><code>console.log(checkNameRequest()); // ["No body or invalid request.", "Not a valid firstName.", "Not a valid lastName."]
console.log(checkNameRequest({body: {
  firstName: 'Jesse'
}})); // ["Not a valid lastName."]
console.log(checkNameRequest({body: {
  firstName: 'Jesse',
  lastName: 'Warden'
}})); // []</code></pre>
<p>Once you put all your predicates in a checker for the request, you can then use it to verify if the request is good and if not, both debug it yourself, as well as send it back so whoever is calling it knows what they did wrong.</p>
<pre><code>var errors = checkRequest(req);
if(errors.length &gt; 0)
{
  // ... return errors
}
else
{
  // ... use the request
}</code></pre>
<p><a name="conclusions"></a></p>
<h1>Conclusions</h1>
<p>You&#8217;ve seen how pure functions allow your code to be predictable, easily unit testable, and prevent you from having to use try/catch to handle errors. Composing many of them together allows you to build a more solid code base.</p>
<p>You&#8217;ve seen how you already use higher order functions all over the place in the existing programming you&#8217;ve probably already done. Passing functions to other functions is commonplace.</p>
<p>You&#8217;ve seen how using list comprehensions allows you not just easily consume data from arrays, but also using them to call and interact with many other pure functions.  In many cases, it results in less code compared to the imperative equivalents.</p>
<p>You&#8217;ve seen how predicates allow you to practice writing pure functions, validate your inputs, and give you great runtime feedback when combined with checkers.</p>
<p>Most importantly, you&#8217;ve probably seen how you can use some functional programming in your existing code base.</p>
<p>In a future post, I&#8217;ll refactor some existing OOP code that illustrates the bubbling problem you run into using pure functions (forcing functions higher up to store the actual mutable data). I&#8217;ll also showcase how this larger amount of pure functions can simplify your unit tests, and how it changes your usage of mocks. Finally, I&#8217;ll show some small tips on how to more easily test some of the async parts of your code.<br />
<a name="additionalresources"></a></p>
<h1>Additional Resources</h1>
<ol>
<li><a href="https://medium.com/javascript-scene/master-the-javascript-interview-what-is-a-pure-function-d1c076bec976#.b63scxoy2">Master the JavaScript Interview: What is a Pure Function?</a></li>
<li><a href="http://reactivex.io/learnrx/">Functional Programming in JavaScript: Array methods tutorial</a></li>
<li><a href="https://medium.com/@cscalfani/goodbye-object-oriented-programming-a59cda4c0e53#.plqpakpm0">Goodbye, Object Oriented Programming</a></li>
</ol>
<h1>Special Thanks</h1>
<p>Thanks a lot to <a href="https://www.linkedin.com/in/andrew-purdon-50286ba">Andrew Purdon</a>, <a href="https://twitter.com/drewbourne">Drew Bourne</a>, <a href="https://twitter.com/jhooks">Joel Hooks</a>, <a href="https://twitter.com/johnlindquist">John Lindquist</a>, <a href="https://twitter.com/search?q=Dan%20Abramov&amp;src=typd">Dan Abramov</a>, <a href="https://twitter.com/_ericelliott">Eric Elliot</a>, <a href="https://twitter.com/nodename">Alan Shaw</a>, <a href="https://twitter.com/trxcllnt">Paul Taylor</a>, <a href="https://twitter.com/jdalton">John-David Dalton</a>, <a href="https://twitter.com/petrillic">Chris Petrilli</a>, and <a href="https://twitter.com/urnamma">Matt Lancaster</a> for helping me learn all this new functional stuff.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://jessewarden.com/2016/08/beginners-guide-to-functional-programming-part-1.html/feed</wfw:commentRss>
			<slash:comments>4</slash:comments>
		
		
			</item>
	</channel>
</rss>
