<?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 Marcos Hernández on Medium]]></title>
        <description><![CDATA[Stories by Marcos Hernández on Medium]]></description>
        <link>https://medium.com/@marcoslhc?source=rss-358c0be51e58------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*lmba0l5itq6pogJnM1aKTQ.jpeg</url>
            <title>Stories by Marcos Hernández on Medium</title>
            <link>https://medium.com/@marcoslhc?source=rss-358c0be51e58------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 30 Nov 2026 10:42:41 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@marcoslhc/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[A functional approach to className management in ReactJS, Part II]]></title>
            <link>https://medium.com/codesyndicate/a-functional-approach-to-classname-management-in-reactjs-part-ii-c8ebc9fa34dd?source=rss-358c0be51e58------2</link>
            <guid isPermaLink="false">https://medium.com/p/c8ebc9fa34dd</guid>
            <category><![CDATA[functional-programming]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Marcos Hernández]]></dc:creator>
            <pubDate>Sat, 15 Apr 2017 22:32:05 GMT</pubDate>
            <atom:updated>2017-04-15T22:32:05.937Z</atom:updated>
            <content:encoded><![CDATA[<p>Part II of a series. Part I is <a href="https://medium.com/codesyndicate/a-functional-approach-to-classname-management-in-reactjs-part-i-bf928970dab6">A functional approach to className management in ReactJS, Part I</a></p><p>This part is even more theoretical… but bear with me, here are important and interesting concepts that could help you in the future. Most of the ideas in this article comes from <a href="https://twitter.com/richhickey">Rich Hickey</a> and <a href="https://medium.com/u/5dccb9bb4625">Kyle</a>.</p><p>In <a href="https://medium.com/codesyndicate/a-functional-approach-to-classname-management-in-reactjs-part-i-bf928970dab6">Part I</a> we ended up with an Object wrapping an Array. This object has some curious behaviors. First, its constructor accepts a function that ultimately is used to unwrap the value. But how do we introduce the actual value with a “static” method called of()? This is a functional pattern: Prepare a value to be treated generically with a protocol or interface, or create a <strong>Unit</strong> for a type. Furthermore, ClassList is closer to a protocol or interface than a “Classical” Object; or better: Is an object with an API that is compliant with a protocol or interface, in Functional Programming that’s said: ClassList is a Type. We’ll talk about that interfaces later in the series. We also added another method called map(); This method accepts a Function that receives the value and returns a new ClassList with a new value transformed by the function. This is a variation of another functional pattern: to <strong>Lift </strong>a function to work with our value, or <strong>Bind</strong> a function to our <em>Type</em>; remember that, will come handy later<em>. </em>Basically we are teaching, or <em>lifting, </em>the function so it knows how to work with our value inside our container.</p><p>An object of a certain <em>Type</em> that has a method map that accepts a function and returns a value of the same <em>Type</em> as the original object is called <em>Functor</em>. The native JavaScript Array is the most common functor. Finally to get our raw value back we <strong>Join </strong>(or <strong>Flatten</strong>,<strong> Flat</strong>)<strong> </strong>our container, in this case in discussion, that would be the ClassList.prototype.getClasses() method.</p><ul><li><strong>Unit</strong> ( or our ClassList.of() method) inserts a value into a container,</li><li><strong>Lift</strong> (or our ClassList.prototype.map() method) let us transform the value inside our container and returns a new container with the transformed value.</li><li><strong>Join </strong>(or our ClassList.prototype.getClasses() method) returns the value.</li></ul><p>Actually, instead of inlining Array.prototype.concat() from our initial ClassList.prototype.getClasses() we could just <strong><em>map</em></strong><em> </em>our list (For consistency and clarity sake I prefer the other way, though someone else could think different than me):</p><pre>ClassList.prototype.concat = function(otherList) {<br>    return this.map((lst) =&gt; lst.concat(otheList.getClasses()));<br>}</pre><p>There is another common operation on lists (and is in the nativeArray.prototype) and is the ability to <strong>Fold</strong> (<strong>Reduce</strong>) the list to a single value. We have an Array.prototype.join() method in ES (not exactly the <strong>Join</strong>, or <strong>Flat</strong>, we talked before; mind you) that reduce the array into a single string, but that doesn’t really help because it is not a general solution. The real way to <em>reduce</em>, or <em>fold</em>, will allow us to do a lot of more stuff like optimizing this repeated calls to filter/map and better yet: learn!</p><p><strong><em>Fold</em></strong>, or <strong><em>Reduce </em></strong>is an operation over a Type where we combine a new element out of it. Let’s try with NativeArray:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/58088ff30490edc5ddeb010068eed41c/href">https://medium.com/media/58088ff30490edc5ddeb010068eed41c/href</a></iframe><p>But we shouldn’t think of reduce in terms of only numeric sums, we could also do strings:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1cae11c5b0cf2f4d52d18c9dcb368c48/href">https://medium.com/media/1cae11c5b0cf2f4d52d18c9dcb368c48/href</a></iframe><p>And sometimes we can get a more complicated element that we began with:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c466b8b23bf0bf26bdfb14a5ea0636bc/href">https://medium.com/media/c466b8b23bf0bf26bdfb14a5ea0636bc/href</a></iframe><p>In sum, what <strong>Reduce</strong> does is <em>accumulate in one single value</em> the results of a repeated operation over each value of the list, the resulting single value could have the shape we want, but it has to be <em>one single value</em>.</p><p>Notice how we returned a function in weirdComputation. In this case we did that so we could pass matrix and keep the function pure, but in the future we are going to do the same to inject the function with external values and delay execution, both useful for composition.</p><p>Now consider this: we have a list of classes: ClassList([&#39;btn__background--solarized&#39;, &#39;btn__text--solarized&#39;, &#39;btn__overlay--solarized&#39;, &#39;btn__icon&#39;, &#39;btn__placeholder&#39;]) and we want to add the--active modifier only to the ones--solarized. It’s not the most practical of examples and mapping over it won’t negatively impact performance or memory, but it will serve for now. We would solve this by filtering first those where the string &#39;--solarized&#39; is part of the class name and then mapping over this filtered list to add the --active modifier. Something like this:</p><pre>ClassList.of([<br>    &#39;btn__background--solarized&#39;,<br>    &#39;btn__text--solarized&#39;,<br>    &#39;btn__overlay--solarized&#39;,<br>    &#39;btn__icon&#39;,<br>    &#39;btn__placeholder&#39;<br>]).filter(str =&gt; /--solarized/.test(str))<br>  .map((str) =&gt; str.concat(&#39;--active&#39;));</pre><pre>ClassList([<br>    &#39;btn__background--solarized--active&#39;,<br>    &#39;btn__text--solarized--active&#39;,<br>    &#39;btn__overlay--solarized--active&#39;<br>]);</pre><p>But going over the list twice (one for the filter and another one for the map) is not performance nor memory friendly, we are repeating an operation and allocating memory twice for the intermediate lists. There must be a better way in which in one step we test if the class has --solarized in it and if so, add --active. That sounds like reducing <em>something</em> to create one new <em>thing</em>. It turns out that by reducing you can <em>filter</em> elements and <em>apply a morphism</em> to the results (map). Lets rework our example to do it that way:</p><p>First let’s implement map and filter as reduce:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0d1f0d4a3509e186b08423d263f940be/href">https://medium.com/media/0d1f0d4a3509e186b08423d263f940be/href</a></iframe><p>In order to apply the filter and the morphism in one step let’s <em>factor out</em> accum.concat and inject it in each function to be able to compose. <em>Beware, we are getting in a higher level of abstraction.</em></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/45699afbb3367ea7f15ec0ffa82aff09/href">https://medium.com/media/45699afbb3367ea7f15ec0ffa82aff09/href</a></iframe><p>There it is! But the last part inside reduce looks very confusing, other programmer will stop a few seconds there before realizing that it’s a function composition, and another few minutes deciphering how the values pass between function. But composition is not difficult at all, let’s define it:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5d8af4f920f00764969fdb8f10a8ed01/href">https://medium.com/media/5d8af4f920f00764969fdb8f10a8ed01/href</a></iframe><p>And we ended up with a transducer, which is a pretty <a href="https://www.youtube.com/watch?v=6mTbuzafcII&amp;t=864s">big thing in Clojure </a>and the FP world generally. And it’s a big thing because we separated the value ingestion process with the ingest() function and the different steps we need to select withfilterReduce(), and transform the data with themapReduce() function, meaning that we just declared what we get and what we needed to do, and leave the implementation details (how we get it and how we work with it) somewhere else. That makes our work easier because we can now reuse our reducers and test them individually.</p><p>Now that we know how to compose filter and mappings to reduce lists, we can change our ClassList.prototype.mapFilter() and ClassList.prototype.filterReduce() methods using just reduce, it will add a few lines of code, but it would be a good test to our understanding and in large lists it would perform better:</p><pre>// original:<br>ClassList.prototype.mapFilter = function(predicate, fn) {<br>  return ClassList.of(this.getClasses())<br>           .filter(predicate)<br>           .map(fn);<br>};</pre><pre>ClassList.prototype.filterReduce = function (predicate, fn) { <br>  return ClassList.of(this.getClasses())<br>           .filter(predicate)<br>           .reduce(fn);<br>};</pre><pre>// Refactor</pre><pre>ClassList.prototype.mapFilter = function(predicate, fn) {<br>  const ingest = (accum, x) =&gt; accum.concat(x);<br>  const reducerFunction = compose(<br>    mapReducer(fn),<br>    filterReducer(predicate)<br>  )(ingest);</pre><pre>  return ClassList.of(this.getClasses())<br>             .reduce(reducerFunction, []);<br>};</pre><pre>ClassList.prototype.filterReduce = function (predicate, fn) {<br>  const reducerFunction = filterReduce(predicate)(fn);</pre><pre>  return ClassList.of(this.getClasses())<br>           .reduce(reducerFunction);<br>};</pre><p><a href="https://gist.github.com/marcoslhc/ceeb9f61d9cc3fd774fac358df292ef2">Here’s the complete code so far</a>, at the very end of the file I made heavy use of arrow functions to shorten the length of the code, some people don’t like it but try to understand what’s happening there. Next week we’ll see a more practical example for this techniques. Until then: happy programming!</p><h3>Addendum: Resources about Transducers</h3><ul><li><a href="https://medium.com/@roman01la/understanding-transducers-in-javascript-3500d3bd9624">Understanding Transducers in JavaScript</a></li><li><a href="https://tgvashworth.com/2014/08/31/csp-and-transducers.html">CSP and transducers in JavaScript</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c8ebc9fa34dd" width="1" height="1" alt=""><hr><p><a href="https://medium.com/codesyndicate/a-functional-approach-to-classname-management-in-reactjs-part-ii-c8ebc9fa34dd">A functional approach to className management in ReactJS, Part II</a> was originally published in <a href="https://medium.com/codesyndicate">CodeSyndicate</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A functional approach to className management in ReactJS, Part I]]></title>
            <link>https://medium.com/codesyndicate/a-functional-approach-to-classname-management-in-reactjs-part-i-bf928970dab6?source=rss-358c0be51e58------2</link>
            <guid isPermaLink="false">https://medium.com/p/bf928970dab6</guid>
            <category><![CDATA[functional-programming]]></category>
            <category><![CDATA[reactjs]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[react]]></category>
            <dc:creator><![CDATA[Marcos Hernández]]></dc:creator>
            <pubDate>Fri, 31 Mar 2017 03:19:05 GMT</pubDate>
            <atom:updated>2017-03-31T03:19:05.864Z</atom:updated>
            <content:encoded><![CDATA[<p>In the not-so-old days, before the “Virtual DOM” and external html templates, we use to do directly manipulate the DOM referencing the node and adding or removing classes from the element `classList`; usually using some library like jQuery or its counterparts and clones. With the arrival of ReactJS and other declarative libraries, this has become ill advised, discouraged and almost impossible.</p><p>There are several helpers in the wild, like <a href="https://github.com/JedWatson/classnames">Jed Watson’s classnames</a> that work perfectly fine and are even more tested than the one I’m proposing here. The problems I’m addressing here are:</p><ol><li>How to manage class names with an API similarly to the DOM’s native ClassList.</li><li>How to handle default and initial classes for an element.</li><li>Avoid nasty errors and exceptions using the default classes.</li><li>And finally address some ideas in Functional Programming (FP) I’ve been working on to create a pointfree API.</li></ol><p>Let’s start with some definitions. I’m starting with a wrapper around the Array type in ES. Mostly because Array is the data structure closer to list in ES. I’m wrapping it in our own implementation because we want this object chainable and keep the same interface until we use the final value. I’m using some ideas inspired by functional programming and ADTs; though may not be fully compliant, and surely not the most performant, they are close enough and easy to reason about.</p><h3>The ClassList Container</h3><p>So let’s start with:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ecc1d664c27dd409ca87df563155fa8d/href">https://medium.com/media/ecc1d664c27dd409ca87df563155fa8d/href</a></iframe><p>So, I started with a <strong><em>pointed functor</em></strong> with other fancy methods. Basically this is a container or box where I store a value and have a series of methods that know how to handle that value. To be more specific. I’m teaching this object how to retrieve a stored value (in the constructor) and how to store a value with the static method of. The of method allow us to put content inside a <em>ClassList </em>Container. In this specific case, we can get the value stored by calling getClasses(); What makes it a <strong><em>“Functor”</em></strong> is the map method that knows how to change the shape (type) of the data inside the container and return a new container with the new data. Since our ClassList shares with the type (and the value it stores is of type) Array we can just delegate the methods to the native implementation.</p><p>This already has a nice functionality. If we give an array of strings we can map over it, change it and use it later, or change it and use it in place. Think about adding a theme to all classes in the element. But wait… sometimes we don’t want to map over and change all the elements in the array, we need some kind of filter, and other handiness like map over the filtered results, and add new elements to the array. Let’s add that.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2b3b2268f87d06d6a58119e7d67ff1be/href">https://medium.com/media/2b3b2268f87d06d6a58119e7d67ff1be/href</a></iframe><p>Notice how we can define filter by reducing the previous array into a new one. Now we have an enhanced Array functional API (there are other things from Array we aren’t implementing like shift, unshift, push and pop. They’re not relevant to the requirements and if nothing else they’re easy to add).</p><p>But notice the concat implementation. Though ES Array accepts any type (Number, String, Array, Object), just adding it to the existing array, that’s not very functional nor true in a “categorical” sense. It seems like behind the scene ES’s Array.prototype.concat takes the argument, checks its type and whether it’s an array, flattens the array and pushes the value; but concat has an specific mathematical meaning: is equivalent as addition or more technically aggregation and is supposed to work only on the same type. So [1,2,3].concat(4) should throw a TypeError, because we can’t aggregate an Array and a number, the correct way should be [1,2,3].concat([4]) that would yield: [1,2,3,4] This is important because in our initialClassList.prototype.concat implementation if we pass a ClassList instance we would get a mixed array. Consider this:</p><pre>const list1 = ClassList.of([&#39;btn&#39;])<br>const laterDefinedList = ClassList.of([&#39;btn-solarized&#39;])</pre><pre>// we use our faulty concat:<br>list1.concat(laterDefinedList);</pre><pre>// we get a mixed type array<br>ClassList([&#39;btn&#39;, ClassList([&#39;btn-solarized&#39;])])<br>    .getClasses().join(&#39; &#39;);</pre><pre>&quot;btn, [Object][Object]&quot;</pre><pre>// when we want an uniform array<br>ClassList([&#39;btn&#39;, &#39;btn-solarized&#39;])<br>    .getClasses().join();<br>&quot;btn btn-solarized&quot;</pre><p>We are going to fix the concat issue, add an interface to aggregate other types by cleaning the input and add a convenient method to get the actual value we want as a final result:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d480ed465530d6ed7bd344f6593c93dd/href">https://medium.com/media/d480ed465530d6ed7bd344f6593c93dd/href</a></iframe><p>We have a convenient API that wraps an array. We’ll come next week with the II part of this series where we will add other niceties.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bf928970dab6" width="1" height="1" alt=""><hr><p><a href="https://medium.com/codesyndicate/a-functional-approach-to-classname-management-in-reactjs-part-i-bf928970dab6">A functional approach to className management in ReactJS, Part I</a> was originally published in <a href="https://medium.com/codesyndicate">CodeSyndicate</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How Functional Programming made me a better programmer]]></title>
            <link>https://medium.com/codesyndicate/how-functional-programming-made-me-a-better-programmer-963beac19efe?source=rss-358c0be51e58------2</link>
            <guid isPermaLink="false">https://medium.com/p/963beac19efe</guid>
            <category><![CDATA[testing]]></category>
            <category><![CDATA[functional-programming]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Marcos Hernández]]></dc:creator>
            <pubDate>Mon, 20 Mar 2017 21:31:52 GMT</pubDate>
            <atom:updated>2017-03-23T16:01:45.597Z</atom:updated>
            <content:encoded><![CDATA[<p>I’ve been programming almost all my adult life. I’ve tried a ton of languages, mostly the mainstream ones; Basic, Pascal, Java, C, PHP, Python, a bunch others, and of course JavaScript. But also I was kept in the Bliss of the holy world of Imperative Programming and Object Oriented Programming.</p><p>So, fast forward to just a couple of years ago. I started to read everywhere the term “Functional Programming” (and its always present companion: Haskell) though not totally alien to me. I knew it was one of the “Formal” methods of programming. It was deeply rooted in Math and Logic and <em>it was totally useless in a real world application</em>. I even used some “functional features” in python and even in JavaScript (later I found out Brendan Eich intended JavaScript as a totally functional languages pretty much like scala before Netscape slapped him with the Business Rules that didn’t include functional programming).</p><p>But still, nowadays I spend plenty of time reading and decided to go deeper into the topic and stumbled into <a href="http://www.paulgraham.com/rootsoflisp.html">this article</a> by Paul Graham (link to the complete article in postscript <a href="http://lib.store.yahoo.net/lib/paulgraham/jmc.ps">here</a>)</p><p>It. Blew. My. Mind. Here are some of the things I learned by applying Functional programming to my code:</p><h3>1. Back to basics: Divide And Conquer</h3><p>One of the foundations of <em>Functional Programming (FP) </em>is the use of <a href="https://en.wikipedia.org/wiki/Pure_function">Pure Functions</a>; that is: when you write your functions, you do it in a way they depend only on the arguments passed and whatever other value is in the scope of that function (in any language that supports FP, functions are values).</p><p>I tried playfully to solve puzzles using this restriction. Little by little I started to see problems in a new (old) way: big challenges only accomplished by decomposing in small, simpler, parts that could be solved using Pure Functions. It was going back to basics: Divide and Conquer; and separate concerns.</p><h3>2. Testing is fun again</h3><p>You know how it goes. You commit to TDD, write your assertions, and with a proud smile on your face, start tackling down all you test failures. But pretty soon one of your classes start using another class to retrieve data, in order to ensure a reliable service you use a singleton (or how I call them: The Demon Lords of the Pastafarian Hell) and you inevitably start investing more time writing mocks than actual coding. Soon you start to realize that your unit tests have become almost an E2E test (or how I call them: <a href="https://en.wikipedia.org/wiki/Extraterrestrial_places_in_the_Cthulhu_Mythos#V">Abominations of Vhrool Planet in the 23rd nebula from Nug and Yeb</a>).</p><p>Ever since I started a more functional approach to my code, I can go back to testing with a saner dependency management. Since a function is pure, it cannot rely on any external resource. How do you resolve this? With delayed evaluation: You derive a new function with the injected dependency, then you can safely call the new function with the injection closed over.</p><p>This means you can keep your mocks minimal and you can inject them directly in your tests, no need to expensive setup before testing.</p><h3>3. Find a new medium to express meaning</h3><p>Another foundation of FP (more like a mantra, at least for me) is that the functional programmer don’t write “instructions” or “recipes” but rather write define things through functions. My code now looks more like a dictionary than a cookbook, and that’s a good thing. Is truly self documented code. I’m defining how the data looks for the purpose. I’m not tossing away regular documentation, you should still write proper documentation; but following other good practices, for example: giving meaningful names to values. Writing short pure functions made my code way more readable and easy to follow.</p><h3>4. Less Code. More Abstraction</h3><p>Now I write less code in each iteration. That comes hand in hand with the divide and conquer concept in point #1. If you organize your code in small functions that solve specific components of the problem, is easy to spot patterns and once you detect a pattern you can abstract functionality and call your abstraction anytime you need it.</p><p>On top of that, if you define your abstractions with composability in mind you can reorder your function to extract and transform your data any way you need. And if you did your homework and have your proper tests, if you break any abstraction trying to refactor, you will immediately notice.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=963beac19efe" width="1" height="1" alt=""><hr><p><a href="https://medium.com/codesyndicate/how-functional-programming-made-me-a-better-programmer-963beac19efe">How Functional Programming made me a better programmer</a> was originally published in <a href="https://medium.com/codesyndicate">CodeSyndicate</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>