<?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 Gediminas Katilevičius on Medium]]></title>
        <description><![CDATA[Stories by Gediminas Katilevičius on Medium]]></description>
        <link>https://medium.com/@zarokas?source=rss-43da0f9415c2------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/2*YpqtQnGsb_AM-bd0ume09g.jpeg</url>
            <title>Stories by Gediminas Katilevičius on Medium</title>
            <link>https://medium.com/@zarokas?source=rss-43da0f9415c2------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 22 Nov 2026 04:07:19 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@zarokas/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[Javascript Functional Programming Principles]]></title>
            <link>https://medium.com/@zarokas/javascript-functional-programming-principles-6238cb75d1a3?source=rss-43da0f9415c2------2</link>
            <guid isPermaLink="false">https://medium.com/p/6238cb75d1a3</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[javascript-tips]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[functional-programming]]></category>
            <dc:creator><![CDATA[Gediminas Katilevičius]]></dc:creator>
            <pubDate>Wed, 31 Jul 2019 05:09:26 GMT</pubDate>
            <atom:updated>2019-07-31T05:15:05.863Z</atom:updated>
            <cc:license>https://creativecommons.org/licenses/by-sa/4.0/</cc:license>
            <content:encoded><![CDATA[<h4>Comparing with math functions</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/639/1*3yzsrB0mMYz2j1r6YalDew.png" /><figcaption>That’s what function looks like in 2D</figcaption></figure><p>The first thing you should ask: what actually is functional programming? As the name suggests — it’s about programming using only functions. And it’s partly correct! Only we should keep in mind, that functional programming is making your functions look more like mathematical functions.</p><p>Wikipedia defines functional programming:</p><blockquote><strong>Functional programming</strong> is a programming paradigm — a style of building the structure and elements of computer programs — that treats computation as the evaluation of mathematical functions and avoids changing-state and mutable data. It is a declarative programming paradigm in that programming is done with expressions or declarations instead of statements</blockquote><p>If we take a look what are the attributes of a mathematical function:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/74/1*US6osKiytcRLcaw63zepuw.png" /></figure><ul><li>This function doesn’t mutate any state or data.</li><li>The function consists of a single expression and never of multiline steps for finding a solution. We can say it’s declarative.</li><li>In any point of time, whatever <em>x</em> argument you give, you’ll get the same result.</li></ul><p>Isn’t it super easy to test these kinds of functions? You don’t need to mock anything, you don’t need to prepare fixture data. Just call the function with an argument and expect a result. Let’s take a better look at how we can take advantage of FP principles and make most of our functions be like <em>f(x)</em>!</p><h3>Pure Functions</h3><p>Math functions are pure. And here are key points of what means for a function to be pure:</p><ul><li>Same arguments must always return the same output.</li><li>The function mustn’t do any visible changes neither for its arguments nor for anything outside its boundary. Otherwise, we’ll have side effects which we want to avoid.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/488/1*IAAuKMnYna6ll0ml9-W9Rg.png" /></figure><p>What if we want a more precise PI value and we’ll change it to 3.141? the <em>calculatePerimeter</em> in impure function and will return different results with the same argument. And then your tests fails and it’s possible, that your software might introduce a bug. The pure function saves you from this hassle.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/468/1*Boy3bZooYm7owNrSWvUp6g.png" /></figure><p>With an impure function, you modify the global count variable and by providing the same argument, you get a different result. This function introduces a side effect which is evil and we want to avoid because a function is unpredictable when it depends on the state of the system.</p><p>If you need more reasons why you should write pure functions, I found a really good and detailed explanation by Alivn Alexander: <a href="https://alvinalexander.com/scala/fp-book/benefits-of-pure-functions">https://alvinalexander.com/scala/fp-book/benefits-of-pure-functions</a></p><h3>Immutability enforced with spread syntax</h3><p>You can solve math functions and get a result, which is either a new constant or a new expression:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/74/1*US6osKiytcRLcaw63zepuw.png" /></figure><p>When <em>x = 2</em>, the answer is a new number 4;</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/115/1*ogJFwvUHYF2MnRY-Ji5YAw.png" /></figure><p>When<em> x = 2</em>, as a result you get a new expression <em>4 + y + c</em>;</p><p>No argument was changed and a result is totally new thing. You should enforce this principle into your functions. Don’t modify your arguments as it could introduce unwanted side effects, which leads to system variables unpredictability. So keep your arguments read-only. And if you ever want to change them, create and use a totally different variable. I’ll show you how you can assure immutability by using a spread syntax.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/489/1*v8-Jo4AeQjPe8fE9qG99fg.png" /></figure><p>… is a spread operator. This means, that everything that’s inside the obj object, is taken not as a single collection of parameters, but as a separate key-value pairs ant put back inside an object.</p><p>So <em>{…obj}</em> is the same as <em>{text: obj.text, viewed: obj.viewed}</em></p><p>Yes, you’ll get the exact same object, but the difference is — it’s <strong>not an old one</strong>. Objects have a very interesting property: If you define the same property with different values, an object would only use the last value defined. example:</p><p><em>{viewed: false, viewed: true} // results in {viewed: true}</em></p><p>or</p><p><em>{text: ‘Hello world’, viewed: false, text: ‘changed text’} // results in {text: ‘changed text’, viewed: false}</em></p><p>so what we have done in <em>setViewed</em> function:</p><ol><li>We spread out obj value <em>{…obj}</em>, and we got the following: <em>{text: obj.text, viewed: obj.viewed}</em></li><li>Then we added a changed property<em> {…obj, viewed: true}</em> and it’s the same as <em>{text: obj.text, viewed: obj.viewed, viewed: true}</em></li><li>And because of how objects work, we got the following result: <em>{text: ‘Hello world’, viewed: true}</em></li></ol><p>The spread operator helped us to easily copy our object into a new object, added new viewed value and in the result, our function returned a totally new object and the old object was not mutated.</p><h3>Memoization</h3><p>Let’s get back to the previous example</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/74/1*US6osKiytcRLcaw63zepuw.png" /></figure><p>if <em>x =2; </em>then<em> f(2) = 4;</em></p><p>Because our function is pure, we already know, that by passing argument 2, we’ll always get the result 4, so next time we don’t need to reevaluate our function.</p><p>Memoization is a <strong>caching</strong> mechanism, which allows saving our computing power by utilizing our storage space. Pay notice, that this is only practical when a set of possible arguments is finite and not lengthy, otherwise, we could encounter a memory leak.</p><p>There are multiple libraries that implement memoization. My favourite one: <a href="https://www.npmjs.com/package/memoizee">https://www.npmjs.com/package/memoizee</a> it’s really easy to implement and use, also there’s type definition package for typescript.</p><p>Here’s a simple example of how it works in code:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/364/1*379a85hD1LOC9h8gLL_5iA.png" /></figure><h3>Higher-order functions</h3><p>Math functions can substitute their argument with another function:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/254/1*JDbjCh39BFOdMMdv3bnxZg.png" /></figure><p>By the way, you can substitute x with any kind of expression. These arguments aren’t bound with any concrete constant, set of constants or methods.</p><p>Let’s say we have two functions:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/432/1*zNZbGSE7BP0jjEJzMNrykA.png" /></figure><p>We could see, that these functions do the same thing, only the sign is different. Let’s refactor by passing a callback as a sum or subtraction.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/556/1*_Dk3QpsIpjD0DP-bXXy0ag.png" /></figure><p>We passed a whole function as a first argument and now our method <em>squared</em> doesn’t depend on the sign or any kind of specific method. This kind of function is known as a <strong>higher-order function</strong>. These kinds of functions should follow one of the following two rules:</p><ol><li>Function must take a function as an argument.</li><li>The function must return a function.</li></ol><p>There are three most common higher-order built-in functions in javascript that we’ll discuss: <em>filter</em>, <em>map</em> and <em>reduce.</em></p><h3>Filter</h3><p><em>Filter</em> function returns a <strong>new</strong> array with the elements of an old array that pass a certain test.</p><p>Let’s say you have an array of numbers. And you only want to have negative numbers.</p><p><em>const data = [0, 15, -6, 44, -42];</em></p><p>imperative way:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/410/1*sUsL1NDOxThg7u1LjxLyLg.png" /></figure><p>Declarative way:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/456/1*Y5XK2e7SfFQ707HRZF63aA.png" /></figure><p>I don’t think there’s much to say about which is a more optimal solution.</p><h3>Map</h3><p><em>Map</em> function returns a <strong>new</strong> array with the elements of an old array that are modified with a specific function.</p><p>Let’s say we want to have an array of all positive numbers. We’ll take advantage of <em>Math.abs()</em> function</p><p>Imperative way:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/400/1*mwnJq1hZ4g1PwwMl5508DA.png" /></figure><p>Declarative way:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/340/1*oAc-voMgxGoshtFUZsushQ.png" /></figure><p><em>Map</em> is a higher-order function and we don’t need to do:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/360/1*N8OPZDloPFdYU8A8Z2a0yA.png" /></figure><h3>Reduce</h3><p><em>Reduce</em> function takes an array and converts it into a single value.</p><p>Let&#39;s get the sum of all numbers</p><p>imperative way:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/421/1*c2rX0ImUJxeFt3G2iqt1MQ.png" /></figure><p>Declarative way:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/512/1*3w_ACckTMW935P3PTAQ36g.png" /></figure><h3>Combining higher-order functions</h3><p>You can even combine these functions. If you want to get the sum of all positive numbers:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/523/1*MQ_q6-1-CPHhb3Xt7RiknA.png" /></figure><h3>Currying</h3><p>Consider having a function, which is dependant upon two parameters:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/98/1*VnbUzzEg4apUO3aCjdvwVg.png" /></figure><p>If<em> x = 2</em>, and <em>y</em> is still unknown, we could simplify our function</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/99/1*O6kJxuIEKldZ2p_2ARxoAA.png" /></figure><p>if after some time you get to know what <em>y</em> is equal to, then you could already solve the function. But until then, you can somehow take advantage of your partial result.</p><p>Memoization is a technique, which allows us to use only part of the arguments and get a result as a partially solved function.</p><p>Mainly there are two reasons to use currying:</p><ol><li>The first part of the function takes time to be computed, and an evaluated new function needs to be reused.</li><li>Decorations</li></ol><p>For the first use case example, we want to fetch a movie from the database by its name and quickly calculate ticket prices for a various number of amounts:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/846/1*AgXGUeVNxJeyCCkf36KAhQ.png" /></figure><p>To make currying work, javascript functions need to have only a single argument, and each such kind of function should take advantage of closures.</p><p>The first call to <em>fetchMovieTicketTotalPrice </em>caches the partial result (the principle is very similar to memoization) and reuses its result for multiple amount arguments.</p><p>The second use case has some rules:</p><ol><li>Each of your decorators must take the same flexibly typed argument which can be <em>undefined</em>.</li><li>The decorator must return a new decorator to ensure currying technique.</li><li>If returning decorator receives an empty argument, it must return the latest decorated argument.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/852/1*Tbc_sLlskP0EDF7iR5ziyg.png" /></figure><p><em>Person1</em> has his name lowercased and gets an age attribute, while <em>person2</em> has its last name uppercase and also gets an age attribute.</p><p>Advantages of this pattern:</p><ul><li>We can keep on going almost infinitely with this decorator chain.</li><li>Each decorator does only one job.</li><li>Adding decorators doesn’t make us modify the existing code.</li><li>Our object isn’t mutated, as decorators return a new or the same object.</li><li>Decorator functions are easily testable, as they are pure functions, so our code is easily maintainable and reusable in a variety of ways.</li></ul><h3>Last words</h3><p>It’s not always possible to have all your functions pure, because sometimes you need to log data, have tracking structures, share state between functions. It’s especially hard to keep purity when implementing some 3rd party libraries as they usually require you to do some imperative work. But knowing and using these principles will lower your systems instabilities and increases maintainability.</p><p>Like what you read? Support me by ordering me a nice, warm cup of coffee <a href="http://ko-fi.com/gekastudio">http://ko-fi.com/gekastudio</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6238cb75d1a3" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>