<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Johann Schuster on Medium]]></title>
        <description><![CDATA[Stories by Johann Schuster on Medium]]></description>
        <link>https://medium.com/@schuster.dev?source=rss-5c5c6e9f5415------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*9DSZZYad4tSn3hPqWHcjZA.jpeg</url>
            <title>Stories by Johann Schuster on Medium</title>
            <link>https://medium.com/@schuster.dev?source=rss-5c5c6e9f5415------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 21:36:23 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@schuster.dev/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Share the UI Event State in React With RxJS]]></title>
            <link>https://medium.com/better-programming/sharing-ui-event-state-in-react-with-rxjs-f7edf5648027?source=rss-5c5c6e9f5415------2</link>
            <guid isPermaLink="false">https://medium.com/p/f7edf5648027</guid>
            <category><![CDATA[react]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[rxjs]]></category>
            <category><![CDATA[reactjs]]></category>
            <dc:creator><![CDATA[Johann Schuster]]></dc:creator>
            <pubDate>Thu, 30 Jan 2020 16:26:03 GMT</pubDate>
            <atom:updated>2020-02-06T17:55:07.471Z</atom:updated>
            <content:encoded><![CDATA[<h4>Share states across components</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*53oW1RCEGI5bcSYkkHFDrg.png" /></figure><p>This piece is a breakdown of a nifty solution to sharing UI event data between React components, which has been a recurring challenge for me over time. It’s a strategy I recently used in a React/ TypeScript project, but it’s applicable to any front-end JavaScript framework.</p><p>This piece is primarily about reactive programming using <a href="http://reactivex.io/">ReactiveX</a> streams, via the<a href="https://rxjs-dev.firebaseapp.com/"> RxJS</a> JavaScript library.</p><h3><strong>The Problem</strong></h3><p>Generally, click handlers (or any UI event handlers) in React are somehow bound to the state, either inside the component or in a parent/child.</p><p>One of the first components we learn to write from the docs is a stateful class, with a handler that increments a value in the state or something. It works — there’s no doubt — but the combination of conforming to a top-to-bottom data flow and remaining in the virtual DOM sphere without querying the document requires trade-offs. Things to keep in mind:</p><ul><li><strong>Reconciliation</strong>: Is all the diffing really worth it for UI events? This has a high impact on low-CPU devices. If your app needs a smooth, complex UI, you’re at risk of blocking the UI because of it.</li><li><strong>Stateful UI components: </strong>If you need to make a request based on a DOM event in another part of the app (example to follow), maintaining a separation of concerns will be a challenge. Remember we want to keep UI components “dumb” and void of business logic.</li><li><strong>Prop threading: </strong>Not the end of the world, but boy do we hate it when there’s a lot of it.</li></ul><p>It’s for the above reasons that using frameworks like React aren’t recommended for TV-based applications.</p><p>I recently needed to access innerHTML data from a component that was multiple children deep in the component hierarchy. On clicking the item, I needed to use its value to make a request in the outer most parent. Like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/720/1*M2HmDF8kGkrdYySmCBDRBg.jpeg" /></figure><p>The UI is determined by the shape of a network response that contains a reference to the component types and data contained within it, so it’s important the list content and request itself be as content-agnostic as possible.</p><h3><strong>The Solution: Rx, BehaviorSubject</strong></h3><p>For the last year or so, I’ve been working on web-based applications that run on a living room TV’s and gaming consoles. The high user expectations Netfilx, Hulu, and other services set — together with the difficulty of building for TV browsers — makes it an interesting challenge, and one tool we have learned to be extremely effective for our needs is RxJS.</p><p>Rx is an implementation of a programming paradigm called <em>reactive programming</em> that’s used across multiple languages — in JavaScript’s case, RxJS. Regardless of your front-end language preference, an event-driven UI can become complex and reach a point where thinking in streams that respond to events as they happen becomes easier to deal with than state changes as events happen.</p><p>The idea here is to store a reference to the value of a selected DOM element and access it in other sections of our application (not limited to the UI, though). We want to subscribe to the values that get emitted by this storage mechanism and update them when the user selects a new one. The implementation is simple and consists of the following steps:</p><ul><li>Create a new BehaviorSubject with a default value (the store that we’ll subscribe to in other components)</li><li>Create a method to update the subscription</li><li>Implement the click handler</li><li>Subscribe to the BehaviorSubject to get the latest emitted value</li></ul><p>The code looks like this in order:</p><pre>// 1: create the BehaviorSubject</pre><pre><em>export </em>const<em> featuredCategory$ </em>=<em> </em>new<em> BehaviorSubject</em>(&quot;&quot;)<em>.pipe</em>(<br>  <em>distinctUntilChanged</em>(),<br>  <em>skip</em>(1)<br>);</pre><pre>// 2: create a method to update the BehaviorSubject</pre><pre>const<em> setfeaturedCategory </em>=<em> </em>(category:<em> string</em>):<em> void </em>=&gt; <em>featuredCategory$.next</em>(<em>index</em>);</pre><p>We can now use the BehaviorSubject to subscribe and update:</p><pre>// 3: Implement the click handler</pre><pre>&lt;li <em>onClick</em>={(category): void =&gt; <em>setfeaturedCategory</em>(category)}&gt;{category}&lt;/li&gt;</pre><pre>// 4: Subscribe to the behaviorSubject to get the latest emitted value</pre><pre>&lt;=== Anywhere in our app ===&gt;</pre><pre><em>import</em> { featuredCategory$ } <em>from </em>&quot;component&quot;;</pre><pre>featuredCategory$.subscribe((category: string): void =&gt; this.setState({ selectedCategory: category }))</pre><p>As you can see, we now read our state with much more simplicity. Below are some great advantages of using this method.</p><ul><li><strong>Composition:</strong> Because Rx is all about streams, it’s easy to use them in combination with other streams if I need to.</li><li><strong>Flexibility:</strong> RxJS ships with a bunch of methods I can use to manipulate my streams as needed — like if I needed to delay the emission of the emitted value only the first time on page load, for example.</li><li><strong>Control: </strong>If I wanted to stop listening to value changes after a certain condition is met, all I have to do is unsubscribe.</li></ul><pre>featuredCategory$.unsubscribe();</pre><p>Pretty cool, eh? We’re only starting to scratch the surface of this powerful tool. I thought about sharing this nifty trick just in case you find yourself in a similar situation. Hope it’s helpful!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f7edf5648027" width="1" height="1" alt=""><hr><p><a href="https://medium.com/better-programming/sharing-ui-event-state-in-react-with-rxjs-f7edf5648027">Share the UI Event State in React With RxJS</a> was originally published in <a href="https://betterprogramming.pub/">Better Programming</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Testing your JavaScript Code]]></title>
            <link>https://codeburst.io/testing-your-javascript-code-95c171c71647?source=rss-5c5c6e9f5415------2</link>
            <guid isPermaLink="false">https://medium.com/p/95c171c71647</guid>
            <category><![CDATA[testing]]></category>
            <category><![CDATA[bdd]]></category>
            <category><![CDATA[tdd]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[jasmine]]></category>
            <dc:creator><![CDATA[Johann Schuster]]></dc:creator>
            <pubDate>Fri, 01 Dec 2017 18:32:57 GMT</pubDate>
            <atom:updated>2017-12-03T13:41:26.874Z</atom:updated>
            <content:encoded><![CDATA[<p>I know what you might be thinking, there are so many languages and frameworks to learn, and so little time. Why should I spend more time on writing tests if my code seems to work fine? The answer is simple, it makes you think and reason better, as well as keeps your code easier to maintain and improves its accuracy. It’s also fun. If you’ve worked on algorithms on Codewars or Hackerrank, you’ve definitely experienced the thrill of your code passing all the test expectations. Testing allows you to write applications with confidence, knowing that your program will run the way you expect it to. Consider a simple add function.</p><pre>const add = (x, y) =&gt; { return x + y }</pre><p>Seems like a nice little pure function to me. But what if it doesn’t exist in the folder you’re working on? Perhaps you forgot to import or export it. What if strings get passed to your function instead of numbers? What if only one parameter gets passed in? What if other functions relied on the output of this function?</p><p>Writing tests for our functions avoid these simple yet expensive mistakes that could happen, and as your app grows, the expense of faulty code increases.</p><p>This article will give you a simple overview of testing your JavaScript code and what you can expect your code to look like when implementing tests.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KfmDDXmfYwAyPBwhegCraQ.jpeg" /><figcaption>Be strong like this guy</figcaption></figure><h4><strong>Types of testing</strong></h4><ul><li><strong>Unit testing — </strong>Testing small chunks of our code to ensure the code is optimal</li><li><strong>Integration testing —</strong> Testing combinations of units and how they work together</li><li><strong>Acceptance testing — </strong>Testing an application in the browser or on a device to analyze the performance of the entire application.</li></ul><p>We will look at unit testing in this article. It enables us to make sure that individual sections of our code are achieving the tasks we assign to them. Two widely used approaches to Unit testing are TDD, and BDD, Test Driven Development and Behavior Driven Development respectively. They are somewhat similar, the main difference being that TDD simply tests our code against a set of expectations and either pass or fails, where BDD describes the behavior of the implemented function, and pass or fail. Both methods require of us to write our tests before actually implementing the code.</p><h4><strong>Test Assertions</strong></h4><p>Test assertions assess our code against a predefined expectation that could be defined by yourself or applied as a method from a library. There are many awesome libraries out there and personally enjoy <a href="https://github.com/mjackson/expect">expect.js</a> . It is very easy to start testing your code, you simply install the package into your app, import it into your file and begin using the methods. You can also use the cdn and place it in a script tag in your html file.</p><p>Here are some of the many methods from expect.js. There are plenty more, check out the docs in the link above.</p><pre>expect(‘something truthy’).toExist();</pre><pre>expect(myObj).toEqual({a:5, b: 10});</pre><pre>expect(block).toThrow([error], [message]);</pre><pre>console.log(‘all tests pass’);</pre><p>Usage is simple, we simply make comparisons between a value and our expectation of it. If there is no error, we are notified that the tests have all passed, if not, we will receive a descriptive message in the console, of the difference.</p><h4><strong>Preventing Immutability</strong></h4><p>The concept of immutability has become very popular in JavaScript. Keeping our objects free from mutations make our programs (and lives) significantly better. When working with libraries like React with Redux, it becomes especially important, because mutations are not allowed. Using a library like immutable.js certainly avoids the problem, but what if the codebase you are working on is using plain es6? This is where expect and <a href="https://github.com/substack/deep-freeze">deepFreeze</a> come in handy.</p><h4><strong>Example test using expect and deepFreeze</strong></h4><pre>// our function<br>const addToList = (list) =&gt; {<br>return list.push([5]); <br>// if we use this tests will fail because .push mutates the array</pre><pre>return list.concat([5]); <br>// if we use this tests will pass because .concat does not mutate</pre><pre>}</pre><pre>// this is a test function<br>const testAddToList = () =&gt; {<br>const before = [];<br>const after = [5];</pre><pre>// check for mutations<br>deepFreeze(before);</pre><pre>// check if result is deeply equal to our expected result<br>expect(<br>     add(before)<br>   ).toEqual(after)<br>}</pre><pre>testAdd();<br>console.log(‘tests pass’)</pre><h4><strong>Behavior Driven Development</strong></h4><p>BDD is a subset of TDD. The difference is that our tests describe the expectations of our functions, instead of just checking whether or not they pass. This method is especially helpful when you have a defined set expectations for a function instead of checking for equality or something. This is where a library like Jasmine comes in. Jasmine is very easy to use and get started with, at first it might be a bit to wrap your head around but it’s certainly worth the effort. The following paragraphs describe an overview of writing a test suite with Jasmine, describing the most important concepts as we go along.</p><h4><strong>The red, green, refactor cycle</strong></h4><p>This is where testing becomes powerful. Following this methodology , we follow a pattern of defining our expectations in our test suite and running the tests. The tests will all return red errors as we have not yet written any code. We then write out the functionality one by one turning the red errors to green passes. When all the expectations are met, we know our function is ready to be implemented.</p><p>When we write a unit test, our expectations for any given function. It can be a simple function that we expect to behave in a certain way. Imagine we wanted to create a digital wallet. We would set the following expectations to get started.</p><ul><li>It should add a bill to our collection</li><li>It should be able to remove a bill</li><li>It should be able to calculate the total</li></ul><p>When we write out a suite in Jasmine, there are three important parts.</p><ul><li>Describe: This invokes the suite (just a regular old function) used to describe a function or part of code.</li><li>It: “It” is a speculation of what a certain part of the function must achieve, called a ‘spec’. A suite can have more than one spec.</li><li>Expectation: What we expect the result of calling the function should be.</li></ul><p>Here is what a test suite in Jasmine looks like.</p><pre>describe(‘Wallet’, function(){<br>  var wallet;<br>  var five, ten, twenty, hundred;<br></pre><pre>// reset vars before each spec runs<br>beforeEach(function(){<br>   wallet = [];<br>   five = 5, ten = 10, twenty = 20, hundred = 100;<br>})</pre><pre>// this is a spec that checks if we can add a bill<br>it(“should be able to add bills”, function(){</pre><pre>   wallet.push(five, ten, twenty)</pre><pre>// our expectation<br>expect(wallet).toEqual([5, 10, 20])</pre><pre>})</pre><pre>// this is a spec that checks if we can remove<br>it(“should be able to remove one bill”, function(){</pre><pre>    wallet.push(five, ten, twenty)</pre><pre>    wallet.splice(wallet.indexOf(5), 1)</pre><pre>    // our expectation<br>    expect(wallet).toEqual([ 10, 20 ])</pre><pre>})</pre><pre>// this is a spec that checks if we can calculate the sum<br>it(“should be able to calculate total”, function(){</pre><pre>    wallet.push(five, ten, twenty, hundred, twenty, five)</pre><pre>    total = wallet.reduce((a,b) =&gt; a + b)</pre><pre>    // our expectation<br>    expect(total).toEqual(160)<br>   })</pre><pre>})</pre><h4><strong>Spying on a function</strong></h4><p>Using Spy, we can can mock the behavior of a function and get insight into how many times the function was called, the value that was returned, and how many arguments the function was called with.</p><pre>// spying on functions<br>function add(a, b, c) {<br>   return a + b + c<br>  }</pre><pre>//our test suite<br>describe(“Add”, function() {</pre><pre>    var spy, result</pre><pre>    beforeEach(function() {<br>    addSpy = spyOn(window, ‘add’).and.callThrough() // execute func</pre><pre>    result = addSpy(8, 5, 7)</pre><pre>})</pre><pre>// spec that checks if the function has been called <br>it(“the function has been called”, function() {</pre><pre>   expect(addSpy).toHaveBeenCalled()</pre><pre>})</pre><pre>// spec that checks value returned<br>it(“can evaluate function excution”, function() {<br>  <br>    expect(result).toEqual(20)</pre><pre>})</pre><pre>// spec that checks if the function was executed once<br>it(“will only be executed once”, function() {</pre><pre>    expect(addSpy.calls.count()).toBe(1)</pre><pre>  })</pre><pre>})</pre><p><strong>Testing asynchronous code</strong></p><p>The done() method in Jasmine allows to to test the response from an API call. We can set an expectation on the call, and the done() function will only return once the call is complete.</p><pre>// Testing async code<br>function getUserInfo(username) {<br>   return $.getJSON(‘https://api.github.com/users/&#39; + username)<br> }</pre><pre>describe(“#getUserInfo”, function() {</pre><pre>it(“return the correct name”, function(done) {<br>      getUserInfo(‘j-schuster’).then(function(data) {<br>      console.log(data)<br>      expect(data.name).toBe(‘Johann Schuster’)<br>      done() // tests the async code, runs when call has completed</pre><pre>     })<br>   })<br> })</pre><p>We have covered a few important concepts in getting started with testing our code. This is just an overview and there are still countless ways to make your code more efficient, but I hope this was helpful in giving you an idea of TDD and BDD testing.</p><p>Are there any testing techniques or libraries that you have found useful? I would love to hear about them :)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YsgkK0zwyfSS5mqEGkqc8A.jpeg" /><figcaption>Party time</figcaption></figure><p>Please give this article a little clap if you found some value in it. Happy Friday!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=95c171c71647" width="1" height="1" alt=""><hr><p><a href="https://codeburst.io/testing-your-javascript-code-95c171c71647">Testing your JavaScript Code</a> was originally published in <a href="https://codeburst.io/">codeburst</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A beginner friendly intro to functional programming Pt2]]></title>
            <link>https://codeburst.io/a-beginner-friendly-intro-to-functional-programming-pt2-eaff59c767fc?source=rss-5c5c6e9f5415------2</link>
            <guid isPermaLink="false">https://medium.com/p/eaff59c767fc</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[functional-programming]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Johann Schuster]]></dc:creator>
            <pubDate>Tue, 07 Nov 2017 15:33:23 GMT</pubDate>
            <atom:updated>2017-11-08T22:05:12.251Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*l3FWfVg-GUWd8ytyaDDMAA.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/photos/Sk-C-om9Jz8?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Dayne Topkin</a> on <a href="https://unsplash.com/?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>This article is part two of “A beginner friendly intro to functional programming”, that establishes why we would consider incorporating functional programming techniques into our code, key traits of the styles, what higher order functions, anonymous functions and recursive functions are. If you’d like to check that out <a href="https://codeburst.io/a-beginner-friendly-intro-to-functional-programming-4f69aa109569">here’s</a> a link.</p><p>The goal of this article is to build on the foundations of the previous one, and to develop our understanding of the ways functions can be combined to create powerful, easy to read and maintain code. By the end, we would hopefully have a clear understanding of applying the powerful methods of partial application, curried functions and function composition to our FP style.</p><p>These concepts can get pretty thorny quickly, and my main goal is to keep things simple, reviewing how functions run will help us easily understand the following concepts.</p><p>Functions in JavaScript can take in any amount of parameters, the amount of parameters included in a function’s declaration determines the function’s arity, which refers to the amount of parameters defined when the function was declared. Because JavaScript allows us to call a function with any number of arguments, we can call any function with less or more arguments than it expects. If we were to check the arity of a function with one parameter, and pass in more than one argument, it will return one. If were to pass in two arguments to a function that expects three, it will still return 3 as its arity length.</p><pre>function unary(a){}<br>function binary(a,b){}<br>function ternary(a,b,c){}</pre><pre>console.log(unary.length) // logs: 1<br>console.log(binary.length) // logs: 2<br>console.log(ternary.length) // logs: 3</pre><p>When a function’s parameters all have values, the function can be applied over its arguments, which is just a function being run. We would say that this is total application of a function, or that the function is fully being fully applied, because it received as many arguments as it expected.</p><p>In JavaScript, every time we run a function, total application happens, even if we didn’t supply the correct amount of arguments. When we supply a function with arguments, they are bound to variables in the function’s lexical scope. When we don’t pass a value to a parameter it gets bound to that function’s scope as undefined, and we know what result that brings. While this approach works, it limits us. Remember that our goal is to write reusable code that’s easy to reuse, test and debug.</p><p><strong>Partial Application</strong></p><p>Partial application is an intelligent way of writing a function so that if we pass in 2 arguments to a function with an arity of 3 (expects 3 arguments) the supplied arguments will get bound to the appropriate values in the function’s scope, and then wait until the final argument is passed in to run the function. In partial application, a function that did not have all it’s parameters bound, will return another function with a new, lower arity function, which will take in less arguments because some have already been partially applied.</p><p>EXAMPLE OF FULL APPLICATION</p><pre>function mapFunc(func, arr){<br>   return arr.map(func);<br>  }</pre><pre>//es6 implementation of above function<br>//const mapFunc = (func, arr) =&gt; arr.map(func);</pre><pre>const double = (num) =&gt; num * 2;<br>const triple = (num) =&gt; num * 3;</pre><pre>console.log(mapFunc(double, [ 7, 3, 9] )); // logs: [14, 6, 18]<br>console.log(mapFunc(triple, [ 7, 3, 9] )); // logs: [21, 9, 27]</pre><p>mapFunc has an arity of 2, we supplied two arguments. The function was fully applied to its arguments.</p><p>If we call mapFunc with one argument:</p><pre>console.log(mapFunc(double)); // “error”</pre><p>EXAMPLE OF A PARTIALLY APPLIED FUNCTION</p><pre>function partialFunc(func){<br>   return function(arr) {<br>     return mapFunc(func, arr);<br>   }<br> }</pre><pre>// es6 implementation of above function<br>//const partialFunc = (func) =&gt; arr =&gt; mapFunc(func, arr);</pre><pre>const doubleItems = partialFunc(num =&gt; num * 2);<br>const tripleItems = partialFunc(num =&gt; num * 3);</pre><pre>console.log(doubleItems([ 7, 3, 5 ])); // logs: [14, 6, 18]<br>console.log(tripleItems([ 7, 3, 5 ])); // logs: [21, 9, 27]</pre><p>If we call our partially applied function with one argument:</p><pre>console.log(partialFunc(double)); <br>// logs: (func) =&gt; arr =&gt; mapFunc(func, arr)</pre><p><strong>Currying</strong></p><p>Currying is a form of partial application. When one calls a curried function without all of its arguments, it returns another function waiting for the next.</p><pre>Simple Curried function<br>   function curried(a) {<br>      return function(b) {<br>         return function(c) {<br>            return a + b + c;<br>          }<br>      }<br>  }</pre><pre>console.log(curried(2)(4)(6)) // logs: 12</pre><p>The curried function is also applied partially, and we could apply each of its functions one at a time until all the parameters have been passed in.</p><pre>const a = curried(2)<br>const b = a(4)<br>const c = b(6)</pre><pre>console.log(c); // logs: 12</pre><p>This works great, but if we wanted to have a function that does something else, like multiply, we would have to write another multiply curried function . We can write a generic curried function that we can pass a function like add or multiply to, we’d be able to reduce our code and use it in many different ways.</p><pre>// Simple pure functions that perform an operation</pre><pre>function add(a,b,c) { return a+b+c; }<br>function multiply(a,b,c) { return a*b*c; }</pre><pre>// Generic curry function</pre><pre>function curry(fn) {<br>  return function curried() {<br>     var args = [].slice.call(arguments);<br>        return args.length &gt;= fn.length ?<br>           fn.apply(null, args) :<br>              function () {<br>                var rest = [].slice.call(arguments);<br>                  return curried.apply(null, args.concat(rest));<br>             };<br>         };<br>     }</pre><pre>var curriedAdd = curry(add);<br>var curryMultiply = curry(multiply)</pre><pre>console.log(curriedAdd(4)(5)(6)); // logs: 15<br>console.log(curryMultiply(7)(8)(9)) // logs: 504</pre><pre>console.log(curriedAdd(4,5)(6)) // logs: 15<br>console.log(curryMultiply(7,8,9)) // logs: 504</pre><pre>// es6 implementation of our generic function<br>function curry(fn) { <br>   return function curried(…args) {<br>      return args.length &gt;= fn.length ?<br>        fn.call(this, …args) : (…rest) =&gt; {<br>          return curried.call(this, …args, …rest);<br>      };<br>   };<br>}</pre><p>Now instead of having one large function with a single purpose, we have a generic one that takes in little functions with definite tasks, applies them to a final input.</p><p>Simply put, what this function does is:</p><ul><li>return a function</li><li>store the arguments we passed to it</li><li>check for the arity of the function</li><li>if we passed in all the arguments we’re done</li><li>if not return a function keeping in mind of all the arguments already passed in, with a lower arity.</li></ul><p>I highly encourage spending some more time learning about currying and partial application, there are many ways to build upon this, seeing that our goal here is to build a perspective of functional programming paradigm, we will move on:) At the end I will include links to some cool resources.</p><p><strong>Function Composition</strong></p><p>Function composition is all about combining little pieces of logic together that make up more complex functions. The idea is to break up a complex task into pieces of testable pure functions.</p><p>We can think of composing functions by linking them together, and the result of one function becomes the input for the next. The result of the final function is the overall result.</p><p>Composed functions evaluate from the inside out, if we have simple composed math function it would look like: f ( g ( x )) and the evaluation would begin with x, then g and the f. We can also write a function to evaluate from left to right which is called a pipeline. The following is an example of a simple pipeline function, if we wanted to inverse the order of evaluation we would use the Array.prototype.reduceRight() javascript method instead of Array.prototype.reduce().</p><p>Simple example of pipeline composition (using es6 for brevity).</p><pre>// add 5<br>const add5 = (num) =&gt; num + 5;<br>// triple<br>const triple = (num) =&gt; num * 3;<br>// add note<br>const note = (str) =&gt; `Your lucky number: ${str}`;<br>// apply<br>const apply = (fn1, fn2) =&gt; fn2(fn1);<br>//compose</pre><pre>const compose = (arr) =&gt; (val) =&gt; arr.reduce(apply, val);<br>const add5AndTriple = compose([add5, triple, note]);<br>console.log(add5AndTriple(4));<br>// logs: “Your lucky number is: 27”</pre><pre>// reusing the functions are easy<br>const demoFunc = compose([add5, triple, add5, triple, note]);<br>console.log(demoFunc(4));<br>// Logs: “Your lucky number is: 96”</pre><p>Simply put, we have three functions, add, triple and note, each focusing on one single task. Our apply function is a predicate that we will use when we make use of the reduce method (remember that the reduce method takes in a function as its first argument). Our compose function takes in an array, and reduces it with the apply function. We partially apply the compose function to a variable which, when called, takes in the value we want to have some transformation done to.</p><p>Given that this is just a basic demonstration, this method becomes very useful when dealing with data that needs operating on. If we had a set of data that needed to filtered, organized and modified, we can easily break up our code into simple testable pure functions, compose them together and export the single function to reuse in our code.</p><p>In the interest of keeping these articles brief and convenient to read, there will be one more to top off this introduction to functional programming that will discuss a few more key and important concepts and break down some of the nifty JavaScript methods that adds value to our functional programming toolkit.</p><p>Check out these awesome resources for learning more about the above mentioned concepts.</p><ul><li><a href="https://www.linkedin.com/pulse/compose-me-function-composition-javascript-kevin-greene/">Compose me That: Function Composition in JavaScript</a></li><li><a href="https://hackernoon.com/javascript-functional-composition-for-every-day-use-22421ef65a10">Functional JavaScript: Function Composition For Every Day Use</a></li><li><a href="https://blog.carbonfive.com/2015/01/14/gettin-freaky-functional-wcurried-javascript/">Gettin’ Freaky Functional w/ Curried JavaScript</a></li><li><a href="https://blog.benestudio.co/currying-in-javascript-es6-540d2ad09400">Currying in JavaScript</a></li><li><a href="https://medium.com/javascript-scene/curry-or-partial-application-8150044c78b8">https://medium.com/javascript-scene/curry-or-partial-application-8150044c78b8</a></li><li><a href="https://hackernoon.com/partial-application-of-functions-dbe7d9b80760">https://hackernoon.com/partial-application-of-functions-dbe7d9b80760</a></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*w0YcpMhPGBRBeQ25G9g-iA.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/photos/cPF2nlWcMY4?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Daniel Cheung</a> on <a href="https://unsplash.com/?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>I really hope this article was helpful to you. If you found some value in it, please give it a little clap, and as always, feel free to comment, share or reach out!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=eaff59c767fc" width="1" height="1" alt=""><hr><p><a href="https://codeburst.io/a-beginner-friendly-intro-to-functional-programming-pt2-eaff59c767fc">A beginner friendly intro to functional programming Pt2</a> was originally published in <a href="https://codeburst.io/">codeburst</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A beginner friendly intro to functional programming]]></title>
            <link>https://codeburst.io/a-beginner-friendly-intro-to-functional-programming-4f69aa109569?source=rss-5c5c6e9f5415------2</link>
            <guid isPermaLink="false">https://medium.com/p/4f69aa109569</guid>
            <category><![CDATA[javascript-tips]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[functional-programming]]></category>
            <category><![CDATA[web-development]]></category>
            <dc:creator><![CDATA[Johann Schuster]]></dc:creator>
            <pubDate>Wed, 25 Oct 2017 19:15:27 GMT</pubDate>
            <atom:updated>2017-10-27T17:51:48.893Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Y82oQ1dOC1jxaKDBYnzH5Q.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/photos/5rAcUaCtMzk?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Sebastien Gabriel</a> on <a href="https://unsplash.com/?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>Functional programming is a highly valued approach to writing code, and it’s popularity is continuously increasing in commercial software applications. Functional programming is a paradigm of writing code and is eloquently put in the introduction of this Wikipedia article:</p><p><em>“ -a style of building the structure and elements of </em><a href="https://en.wikipedia.org/wiki/Computer_program"><em>computer programs</em></a><em> — that treats </em><a href="https://en.wikipedia.org/wiki/Computation"><em>computation</em></a><em> as the evaluation of </em><a href="https://en.wikipedia.org/wiki/Function_(mathematics)"><em>mathematical functions</em></a><em> and avoids changing-</em><a href="https://en.wikipedia.org/wiki/Program_state"><em>state</em></a><em> and </em><a href="https://en.wikipedia.org/wiki/Immutable_object"><em>mutable</em></a><em> data. It is a </em><a href="https://en.wikipedia.org/wiki/Declarative_programming"><em>declarative programming</em></a><em> paradigm, which means programming is done with </em><a href="https://en.wikipedia.org/wiki/Expression_(computer_science)"><em>expressions</em></a><em> or declarations instead of </em><a href="https://en.wikipedia.org/wiki/Statement_(computer_science)"><em>statements</em></a><em>.”</em></p><p>We will get into what this exactly means very soon, but first, let’s get the fundamentals out of the way by providing some context. This article serves the purpose of hopefully introducing the fundamental concepts of functional programming to you and by the end of it, we’d have established a basic understanding of why we would choose to apply it into our coding styles, how it relates to JavaScript and some basic patterns that you can begin implementing into your code. Be on the lookout for a second article that will build on this one and dig even deeper into the ideas discussed here.</p><p>The roots of functional programming lie in Lambda calculus, which was a system developed in the 1930’s to express computation using functions similar to what we will see very soon. For quite a while, functional programming concepts and languages were widely discussed in academia and scholarly contexts and eventually bled into the development of commercial software. What makes a programming language functional or not is its ability to facilitate the functional programming paradigm, languages like these are Ruby, Python, Julia and JavaScript, the latter of which has properties of imperative, object-oriented and functional paradigms.</p><p>Let’s look at an example of using an imperative, and then a functional approach to completing a single task.</p><p><strong>Imperative:</strong></p><pre>const arr = [1, 2, 3, 4, 5, 6 ,7 ,8 ,9]</pre><pre>function getOdds(arr){<br>   let odds = [ ];</pre><pre>    for(let i = 0; i &lt; arr.length + 1; i++){<br>          if ( i % 2 !== 0 ){<br>             odds.push( i )<br>          };<br>        };<br>    return odds<br>  };</pre><pre>console.log(getOdds(arr))<br>// logs [1, 3, 5, 7, 9]</pre><p><strong>Functional:</strong></p><pre>function getOdds2(arr){<br>   return arr.filter(num =&gt; num % 2 !== 0)<br>}</pre><pre>console.log(getOdds2(arr))<br>// logs [ 1, 3, 5, 7, 9 ]</pre><pre>// this can be even shorter<br>const getOdds3 = arr =&gt; arr.filter(num =&gt; num % 2 !== 0)</pre><pre>console.log(getOdds3(arr))<br>// logs [ 1, 3, 5, 7, 9 ]</pre><p>Aside from the obvious improvements the functional approach makes, like shorter code, saving us a couple of keystrokes, and the fact that it’s much easier to understand at a quick glance, it’s also elegant, which results in cleaner code, simplifies debugging, testing and maintenance.</p><p>Let’s break this down a bit, so that we can reach a clear understanding of the differences between the two approaches and define what functional programming is.</p><p>In the first approach we are imperatively describing every event that needs to take place in order for us to achieve the task of filtering out the odd numbers from an array. We feed a function an array, inside the function we create an empty array which we will use to store the odd numbers in. We tell it to loop over the array, then we declare a conditional, if the current index is an odd number, push it to the empty one. The for loop does not include the last number in the array, it only includes the numbers leading up to it, so if our last number is odd, it won’t be included. Therefore we add +1 when defining the amount of iterations our loop needs to make.</p><p>In the second approach, we simply define the outcome we want to see by using a method called filter, and allow the machine to take care of all the steps in between. This is a more declarative approach. We declare what the end result must be, and we the rest is handled for us.</p><p>Now we can see what the above mentioned definition strives to express. A way of programming, using declarations and expressions, rather than statements. This definition only scrapes the surface of functional programming, and we will continually build on our definition as our understanding grows.</p><p>Some differences between iterative and functional approaches.</p><ul><li>Stylistically, we define a problem and the changes we would like to see, as opposed to explaining it step by step.</li><li>We do not need to manage state in our functions like above where we managed the state of our empty array.</li><li>We don not have to worry as much about the order of execution.</li><li>We use less loops, conditions and use more built in methods, reusable functions and recursion.</li></ul><p>By using this approach, we ultimately write cleaner code which as mentioned above, helps us in debugging and maintenance. It keeps things modular, and sections of our code is broken down into smaller pieces that we can test with ease. We can reuse parts of our code using helper functions and lastly, it’s a more efficient, mathematical approach to write code.</p><p><strong>The Pillars: </strong>Our coding toolkit for writing functional code</p><p>The following are a few important aspects to writing high quality functional code. Seeing that this is an overview, we won’t dive in too much into each, instead we will just define a few key characteristics and one example of each.</p><p><strong>Pure Functions:</strong></p><p>Pure functions return a value solely based on what was passed into it. The idea behind it is that it will be a pure function if it always returns the same result if the same values are passed into it, and it doesn’t modify values outside of ts scope, that makes it independent from any state in the system. Therefore, a pure function can never mutate data, produce no side effects and can be easily reused. An example of a non pure function will be a function that makes an API call or returns an unpredictable result.</p><p><strong>Simple Impure function:</strong></p><pre>var tip = 0;</pre><pre>function calculateTip( mealTotal ) {<br>   tip = 0.15 * mealTotal;<br>}</pre><pre>calculateTip( 150 )<br>console.log(tip)</pre><p><strong>Simple Pure function:</strong></p><pre>function isPure(x,y) {<br>  return x * y<br>}</pre><pre>console.log(isPure(3,5));</pre><p>The pure function will return the exact result every time, and it doesn’t mutate any data outside of it. The important thing to pay attention to is that a pure function must stay away from mutating data whatsoever, so be careful when selecting which methods to use inside your pure functions. For instance, if you wish to merge two arrays inside your function, as one would typically do in a React reducer, avoid using the Array.prototype.push( ) method. Instead you’d want to use Array.prototype.concat( ), which will preserve the state of the old arrays and return a new one for your use.</p><p><strong>Higher order functions:</strong></p><p>In Javascript, functions are treated as objects, therefore we can pass functions around as we would any other value. A higher order function is simply a function that operates on other functions. They can take in a function as input, or return one as output. We will see a simple example in the following demonstration.</p><p><strong>Anonymous Functions:</strong></p><p>Anonymous functions are very helpful when we need to define ad hoc logic as we need. As the name implies, an anonymous function in nameless, and mostly found as an argument to a function as a replacement for a named function, a function assigned to a variable, or returned as a function in a higher order function. It’s roots lie heavily in Lambda calculus and is very important to all functional programming languages.</p><p>Anonymous function assigned to a variable. Easy to pass around and invoke when needed.</p><pre>const myVar = function(){console.log(‘Anonymous function here!’)}</pre><pre>myVar()</pre><p><strong>Anonymous function as argument</strong></p><pre>setInterval(function(){console.log(new Date().getTime())}, 1000);</pre><p><strong>Anonymous functions within a higher order function</strong></p><pre>function mealCall(meal){<br>   return function(message){<br>     return console.log(message + “ “ + meal + ‘!!’)<br>    }<br> }</pre><pre>const announceDinner = mealCall(‘dinner’)<br>const announceLunch = mealCall(‘breakfast’)</pre><pre>announceDinner(‘hey!, come and get your’)<br>announceLunch(‘Rise and shine! time for’)</pre><p><strong>Recursion</strong></p><p>Recursion is a well known functional programming technique. A recursive function is simply a function that calls itself, and therefore acts as a loop executing the same code multiple times. It comes with one caveat though, one must be careful to avoid infinite recursions. Therefore a base case is needed, to tell it when to stop. Recursive functions or algorithms can both be implemented using recursion and loops, but it’s better to use recursion. Below is the well know algorithm for factorizing a number both using recursion and a loop.</p><p><strong>Recursive function</strong></p><pre>function factorialize(num){<br>   if (num === 0 || num === 1){return 1;}<br>     return (num * factorialize(num — 1));<br>   }</pre><pre>var result = factorialize(14);</pre><pre>console.log(result);</pre><p><strong>Recursion using a loop</strong></p><pre>function factorialize(num) {<br>  if (num === 0 || num === 1){<br>    return 1;<br>  }<br>  for (var i = num-1; i &gt;= 1; i-- ) {<br>     num *= i;<br>   }<br> return num;<br>}<br>console.log(factorialize(6));</pre><p>We have covered a few of the essential ingredients to writing functional code. It is not possible to always write functional code in an application, but the benefits are great when used as much as possible. Frameworks like Angular and React are heavily influenced by functional programming, and libraries like Redux and Lodash enable us to utilize the benefits of it, so there’s definitely a big benefit to start think in the FP way.</p><p>Resources for learning more? Here are some great articles and resources for further learning.</p><ul><li><a href="https://medium.com/javascript-scene/why-learn-functional-programming-in-javascript-composing-software-ea13afc7a257">Why Learn Functional Programming in JavaScript? by Eric Elliot</a></li><li><a href="http://eloquentjavascript.net/">Eloquent JavaScript</a> by Marijn Haverbeke</li><li><a href="https://medium.com/@cscalfani/so-you-want-to-be-a-functional-programmer-part-1-1f15e387e536">So you want to be a Functional Programmer</a> by <a href="https://medium.com/@cscalfani?source=post_header_lockup">Charles Scalfani</a></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IQhAOkIruj1N39jF8H13CQ.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/photos/hfv2GImBsfM?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Patrick Fore</a> on <a href="https://unsplash.com/?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>I really hope this was helpful and in the next article we’ll dive a little deeper and unpack even more interesting and helpful tools like JavaScript methods, partial application, currying, argument binding and more.</p><p>Feel free to clap, share, critique or share any thoughts on the topic!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4f69aa109569" width="1" height="1" alt=""><hr><p><a href="https://codeburst.io/a-beginner-friendly-intro-to-functional-programming-4f69aa109569">A beginner friendly intro to functional programming</a> was originally published in <a href="https://codeburst.io/">codeburst</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>