<?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 Gabriel Montes on Medium]]></title>
        <description><![CDATA[Stories by Gabriel Montes on Medium]]></description>
        <link>https://medium.com/@gab_montes?source=rss-e19f71e319fa------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*IEiva4uj_I-pBwNJLnMa0w@2x.jpeg</url>
            <title>Stories by Gabriel Montes on Medium</title>
            <link>https://medium.com/@gab_montes?source=rss-e19f71e319fa------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 04:55:52 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@gab_montes/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[Bitcoin Esencial: Claves sobre claves privadas, públicas y direcciones]]></title>
            <link>https://medium.com/@gab_montes/bitcoin-esencial-claves-sobre-claves-privadas-p%C3%BAblicas-y-direcciones-148f854b822d?source=rss-e19f71e319fa------2</link>
            <guid isPermaLink="false">https://medium.com/p/148f854b822d</guid>
            <category><![CDATA[criptografia]]></category>
            <category><![CDATA[bitcoin]]></category>
            <category><![CDATA[software]]></category>
            <dc:creator><![CDATA[Gabriel Montes]]></dc:creator>
            <pubDate>Sun, 29 Oct 2017 22:14:38 GMT</pubDate>
            <atom:updated>2017-10-29T22:14:38.472Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ES4jzKbeyRUi2HOhuhhlXQ.png" /><figcaption>Keys image based on <a href="https://www.pexels.com/photo/close-up-keys-metal-safety-333838/">https://www.pexels.com/photo/close-up-keys-metal-safety-333838/</a></figcaption></figure><p>Hace tiempo que tenía ganas de comenzar a escribir una serie de artículos para que quienes quieran aprender qué es y como funciona Bitcoin, puedan arrancar leyendo sobre algunos conceptos básicos pero desde una perspectiva lo más simple posible.</p><p>Ayer sábado por la mañana, pasé por la increíble NodeConfAr edición 2017 y me crucé con el gran <a href="https://medium.com/u/9e165ef458c4">Hernan Rajchert</a>, con quien tuvimos una muy linda conversación sobre claves, direcciones y otros temas esenciales de Bitcoin.</p><p>A continuación, algunos de los conceptos sobre los que estuvimos charlando.</p><h3>Tus claves, tus bitcoins</h3><p>Como muy bien dice <a href="https://medium.com/u/898f59563d67">Andreas M. Antonopoulos</a>: “Son tus claves, son tus bitcoins. No son tus claves, no son tus bitcoins”. Eso resume en muy pocas palabras algo fundamental: como la red Bitcoin utiliza criptografía para asegurar que solo uno puedas utilizar sus bitcoins, mantener segura y secreta la clave privada es la única forma de mantener seguros los bitcoins.</p><p>Si cualquier otra persona llegase a conocer esa clave privada, podría utilizar esos bitcoins ya que el sistema no tendría forma de distinguir entre el dueño y el “falso” dueño. De alguna manera, la clave privada es la “prueba de identidad” necesaria para que la red acepte cualquier movimiento de esos bitcoins.</p><p>Por otro lado, si se perdiera la clave privada, esos bitcoins quedarían inmovilizados por el resto de la eternidad, literalmente. Bitcoin no tiene opción de “recuperar mi clave”. El motivo es parte del típico dilema de la seguridad vs. la facilidad de uso. En este caso, bien vale el costo de perder un poco de usabilidad y no poder recuperar claves porque el beneficio es tener un sistema de máxima seguridad y prácticamente inviolable.</p><p>Habiendo quedado claro que las claves privadas hay que mantenerlas a salvo y fuera del alcance de amigos de lo ajeno, veamos cómo se crean y como se pueden almacenar.</p><h3>Esquema de claves y direcciones</h3><p>Para asegurar que los bitcoins registrados en la <em>blockchain</em> solo puedan ser utilizados por su dueño (*), la red de Bitcoin exige que cualquier movimiento de fondos o transferencia, sea firmada digitalmente por aquel para ser considerada válida.</p><p>Bitcoin utiliza un algoritmo llamado ECDSA para derivar de una clave privada, la clave pública correspondiente y así poder validar las firmas digitales hechas con esa clave privada.</p><p>En este esquema, cualquier (**) número de 256 bits o 32 bytes puede ser una clave privada válida. Por lo tanto, solo basta con calcular el SHA256 de cualquier cadena de caracteres para obtener una clave privada válida.</p><p>Las claves públicas, a su vez, pueden tener 256 o 512 bits dependiendo si están o no comprimidas, a los cuales se les suma un byte adicional como prefijo indicativo del tipo de clave pública en cuestión. Por lo tanto, las claves públicas son siempre de 33 o 65 bytes.</p><p>Quizá para ahorrar espacio en la <em>blockchain</em> y facilitarle la vida a los usuarios, existe una alternativa adicional a utilizar una clave pública de ese tamaño: crear una “dirección” al reducir esa clave pública a 160 bits a partir de aplicar SHA256 y luego RIPEMD-160 sobre la clave pública. Estas direcciones usualmente son cadenas de texto de alrededor de 34 caracteres (***) y comienzan con “1” (****).</p><p>Es importante destacar que si bien de la clave privada se deriva la pública, y de ésta la dirección, no es posible realizar el camino inverso. De ahí la seguridad de que haciendo pública la clave pública o la dirección, no es posible para un tercero conocer o encontrar la clave privada que las generó.</p><h3>Claves derivadas</h3><p>Aprovechando que el espacio de direcciones es inmensamente grande (entre 2^160 y 2^256) y con el objetivo de disminuir riesgos y aumentar la privacidad de los usuarios, es que se recomienda no reutilizar direcciones sino ir creando direcciones nuevas para cada nueva transacción.</p><p>Esto supondría un serio problema para el usuario o los programas utilizados para transar bitcoins, billeteras, que tendría que guardar y asegurar un número creciente de claves privadas.</p><p>Para mitigar este inconveniente, y aprovechando otra vez las bondades de la criptografía, se diseñó un esquema seguro de derivación de claves privadas (BIP32). En este esquema, se parte de una única semilla o <em>seed </em>de 128 bits, la cual se introduce en un generador de números pseudoaleatorios para ir obteniendo distintas claves privadas de 256 bits de forma determinísca. A su vez, a partir de esas claves privadas se derivarán las correspondientes claves públicas y direcciones a medida que vayan siendo necesarias. La mayoría de las billeteras utilizan este esquema, cuidando la privacidad de los usuarios.</p><p>Si un usuario perdiera su billetera o deseara utilizar sus bitcoins en otro dispositivo, solo debería volver a introducir la semilla para regenerar las mismas claves y las mismas direcciones. De ahí la importancia del determinismo del algoritmo de derivación.</p><p>En esos casos, esta “clave maestra” o semilla de 128 bits es la que debe ser guardada con el mayor cuidado. Si esa clave estuviera comprometida, todas las claves privadas derivadas estarían comprometidas también. Evidentemente las claves privadas derivadas también deben mantenerse secretas pero el riesgo de que una fuera conocida por un tercero solo afectaría a los bitcoins relacionados con esa única clave privada.</p><h3>12 palabras clave</h3><p>Gracias a otro esquema muy inteligente llamado BIP39, los humanos tenemos una forma sencilla de recordar o almacenar de manera segura esas semillas de 128 bits: a través de 12 palabras que caben hasta en una servilleta.</p><p>Este esquema define un diccionario de 2048 palabras. Cada palabra tiene asignados 11 bits (del 0x000 al 0x7FF) y fue seleccionadas de forma tal que sea sencillas y que sus 4 primeras letras sean distintas de cualquier otra palabra del diccionario, evitando confusiones entre palabras similares. Sumando 12 de estas palabras se obtienen entonces 132 bits, de los cuales 4 son utilizados para detección de errores, quedando los 128 bits restantes para formar la semilla.</p><p>Es por ese motivo que la mayoría de las billeteras nos exigen hacer una copia de seguridad de esas famosas 12 palabras aleatorias antes de comenzar a operar. ¡Más vale hacerlo y mantener nuestros bitcoins bajo control!</p><h4>Notas</h4><ul><li>(*) Para ser estrictos, todos los bitcoins registrados tienen una prueba asociada que hay que pasar par poder utilizarlos. En aproximadamente el 90% de los casos, dicha prueba consiste en validar que la firma digital de la transacción que los use coincida con la clave pública registrada en dicha prueba. En este caso, solo aquel con la clave privada correspondiente podrá firmar la transacción, pasar la prueba y mover esos bitcoins.</li><li>(**) En realidad, cualquier valor entre 0x0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0001 y 0xFFFF FFFF FFFF FFFF FFFF FFFF FFFF FFFE BAAE DCE6 AF48 A03B BFD2 5E8C D036 4140 es una clave válida ECDSA. Casi, casi 2^256…</li><li>(***) Por la forma de codificar los 160 bits utilizando Base58Check, las direcciones pueden tener entre 26 y 35 caracteres en total.</li><li>(****) Bitcoin define varios tipos de direcciones y las identifica por su caracter inicial. Las que comienzan con “1” son direcciones relacionadas con una clave pública de la red principal o MAINNET. Si una dirección comienza con “m” o “n” corresponde a la red de prueba o TESTNET.</li></ul><h4>Referencias (en inglés)</h4><ul><li><a href="https://bitcoin.stackexchange.com/questions/32639/why-does-the-default-miner-implementation-use-pay-to-pubkey/32642">https://bitcoin.stackexchange.com/questions/32639/why-does-the-default-miner-implementation-use-pay-to-pubkey/32642</a></li><li><a href="https://en.bitcoin.it/wiki/Address">https://en.bitcoin.it/wiki/Address</a></li><li><a href="https://en.bitcoin.it/wiki/Base58Check_encoding">https://en.bitcoin.it/wiki/Base58Check_encoding</a></li><li><a href="https://en.bitcoin.it/wiki/Elliptic_Curve_Digital_Signature_Algorithm">https://en.bitcoin.it/wiki/Elliptic_Curve_Digital_Signature_Algorithm</a></li><li><a href="https://en.bitcoin.it/wiki/List_of_address_prefixes">https://en.bitcoin.it/wiki/List_of_address_prefixes</a></li><li><a href="https://en.bitcoin.it/wiki/Private_key">https://en.bitcoin.it/wiki/Private_key</a></li><li><a href="https://en.bitcoin.it/wiki/SHA-256">https://en.bitcoin.it/wiki/SHA-256</a></li><li><a href="https://github.com/bitcoin/bips/blob/master/bip-0032.mediawiki">https://github.com/bitcoin/bips/blob/master/bip-0032.mediawiki</a></li><li><a href="https://github.com/bitcoin/bips/blob/master/bip-0039.mediawiki">https://github.com/bitcoin/bips/blob/master/bip-0039.mediawiki</a></li><li><a href="https://medium.com/@alcio/a-look-at-bitcoin-non-standard-outputs-c97f65cccbb6">https://medium.com/@alcio/a-look-at-bitcoin-non-standard-outputs-c97f65cccbb6</a></li><li><a href="https://p2sh.info/">https://p2sh.info</a></li><li>Understanding Bitcoin: Cryptography, Engineering and Economics by Pedro Franco, Wiley, 2015</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=148f854b822d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Lego: amazing bricks, awful Facebook login]]></title>
            <link>https://medium.com/@gab_montes/lego-amazing-bricks-awful-facebook-login-4363aea93a67?source=rss-e19f71e319fa------2</link>
            <guid isPermaLink="false">https://medium.com/p/4363aea93a67</guid>
            <category><![CDATA[user-experience]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[lego]]></category>
            <dc:creator><![CDATA[Gabriel Montes]]></dc:creator>
            <pubDate>Sat, 11 Feb 2017 22:01:32 GMT</pubDate>
            <atom:updated>2017-02-11T22:01:32.910Z</atom:updated>
            <content:encoded><![CDATA[<p>I started playing with Lego bricks around 1980 when dad and mom gave me one of the best presents I’ve ever received: the space transport <a href="http://lego.wikia.com/wiki/918_Space_Transport">set 918</a>! It was released in 1978 but Argentina customs blocked most of anything coming into the country so I guess (but cannot assure) they had to do some “tricks” to get it to me.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/715/1*vRTF--K-FhHBVmlSbgPgSQ.jpeg" /><figcaption>I still have the instruction manual of the 918 set! For a 35-years old piece of paper, I think is in a reasonable good shape.</figcaption></figure><p>I played alone and with friends, some of them did not have a chance to get any Lego bricks (too expensive) and some of them had sets I knew for sure I would never have the chance of having (extremely expensive). Anyway, all was joy, imagination and creativity.</p><p>At that time I spent many, many hours creating my own ships, cars, rockets mixing and matching bricks from all the sets I had. I even draw my own instructions in grid sheets using basic isometric perspective to build my loved creations again and again. I could only dream on having my own creations being transformed in actual Lego sets.</p><p>But the advances in technology and Internet cannot be stopped. And almost 30 years later, Lego offers the possibility of doing what at that time was absolutely unthinkable: put your own creations into a world-wide selection process to pick the best proposals and became official Lego sets: <a href="https://ideas.lego.com/">Lego Ideas</a>.</p><p>A few days ago, browsing Soyuz rocket images on the Internet I stumbled upon one belonging to a <a href="https://ideas.lego.com/projects/125044">Lego set proposal</a> that is just awesome and I decided to send my supporting vote!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/660/1*6ugN82c5Qpk5vRYl7JjKUQ.jpeg" /><figcaption>Amazing set by <a href="https://twitter.com/@LuisPG2014">@LuisPG2014</a>. If you like it as much as I do, go to Lego Ideas and click the “Support” button!</figcaption></figure><p>So, in order to express my support, I clicked the blue “Support” button that is on the right side of the page, below the supporters count and the days remaining to reach 10,000 supporters and move to the next stage…</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/987/1*sVFEmQDeQ8zqibEuxsB7xw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/987/1*Tc1E7Sa0ar6ylfW4mcopPA.png" /><figcaption>If not logged in, clicking Support opens a dialog.</figcaption></figure><p>As expected, a dialog opened saying I had to log in. Fair enough. I understand that is needed to properly validate my vote, which is OK. So I next clicked the “Login” button to create my brand new Lego account and vote!</p><p>As I don’t expect to use my brand new Lego account that often, I didn’t feel like creating a new account. One of the biggest issues these days is to have too many logins and passwords, one for each different site!</p><p>But as popular social networks as Facebook, Twitter and Internet companies like Google allow you to use their authentication mechanisms to log into other sites, leading you to less credentials to remember at the cost of some loss of privacy and increased risk in case your main credentials are compromised.</p><p>So I decided to take the Facebook login route, as my new Lego account was not that critical. To be honest, what additional harm could someone with access to my Facebook account do by having access to my Lego account too?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/987/1*A5IYXZfpVw6sC77g4asq2w.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/987/1*4LQpWJWBQd5p5fxeP2ncTw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/770/1*AUEIeNz9VCDoCIRhFC6ViA.png" /><figcaption>Creating a new account and using Facebook authentication is the easiest way! Or perhaps is not…</figcaption></figure><p>Lego asked Facebook some information about me, as my name, profile picture, age, gender and email address. Basic information that, except for the email address, is public. So is OK: Facebook, give that to Lego, please.</p><p>But going back to Lego’s site… surprise! Still asking for my birthday and even my email account!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/987/1*LtpoRkc4TLJt8nRpJtHf3A.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/987/1*aqon-SL3ujltL1PCX3nhFg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/987/1*VlAt6I6F8xWjT8szAeaitA.png" /><figcaption>Lego account creation… what did you do with the info Facebook gave you, Lego!?</figcaption></figure><p>Lego, what did you do with the information Facebook gave you about me? Did you just sent it to <strong>/dev/nul</strong>? I can understand you did not pick a username for me. But the rest of the information is there, guys.</p><p>I count up to <strong>1010</strong> in binary to calm down a bit (!) before moving on. But I could not… The next step asked me to validate my email address!!!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/987/1*6-_EOttYR3ZMgto-P0hhHQ.png" /><figcaption>I still need to validate my email!?</figcaption></figure><p>The whole idea of using a social network go authenticate a user is to gather that information instead of asking the user to give it “manually” to you.</p><p>The whole idea is to gather information that is already validated by the social network itself!</p><p>The whole idea is to help the user to click less to do something!</p><p>The whole idea is… the whole idea is…</p><p>Dear Lego website developers, if you give your lovely users the option to log in using social networks, and your lovely users grant you access to their private data, please use that information and take it as valid, instead of asking the users that same information all over again.</p><p>Making the new user registration workflow easier is key to have more logins, more feedback from your users, more data to gather, analyze and grow your business. Don’t let your desperate apetite for user’s data to provoke the opposite effect, making your potential new users to drop out before completing the registration.</p><p>Almost 30 years later, I do not play with Lego bricks anymore. No hard feelings: I play with bigger, more complex and more expensive toys now but this is a different story!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4363aea93a67" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Is async/await a step back to JavaScript?]]></title>
            <link>https://medium.com/@gab_montes/is-async-await-a-step-back-to-javascript-95e31263dd31?source=rss-e19f71e319fa------2</link>
            <guid isPermaLink="false">https://medium.com/p/95e31263dd31</guid>
            <category><![CDATA[functional-programming]]></category>
            <category><![CDATA[asynchronous]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[react]]></category>
            <dc:creator><![CDATA[Gabriel Montes]]></dc:creator>
            <pubDate>Mon, 19 Dec 2016 19:52:00 GMT</pubDate>
            <atom:updated>2016-12-19T19:52:00.810Z</atom:updated>
            <cc:license>http://creativecommons.org/publicdomain/zero/1.0/</cc:license>
            <content:encoded><![CDATA[<h4>Thoughts on the famous pair of magic keywords, promise chains and a bit of functional programming</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/748/1*viflUdbednDFXmgOWAQpzA.png" /><figcaption>Using <strong>async/await</strong> in a function that handles a request.</figcaption></figure><h4>From callbacks to promises</h4><p>By the end of 2015, I started to hear about a new set of keywords coming into the JavaScript world that would save us from the promise chain hell, which, in turn, saved us from callback hell! I remember those were exciting times, while trying to understand how <strong>async/await</strong> worked under the hood and how that magic couple was going to simplify our developer lives once and for all.</p><p>Lets see some examples to understand how we get to <strong>async/await</strong> in the first place. Lets imagine we are working on our API and have to respond a request by a series of asynchronous operations:</p><ul><li>check the user is valid</li><li>gather data from the database</li><li>gather data from an external service</li><li>manipulate and write data back to the database</li></ul><p>Let’s also suppose we do not have any knowledge of promises yet, because we traveled back in time a couple of years, so we use a <strong>callbacks-based</strong> code to deal with the request. The solution would be something like the following:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/439b82f845083d74c449de9209651b65/href">https://medium.com/media/439b82f845083d74c449de9209651b65/href</a></iframe><p>And this is the so-called <strong>callback hell</strong>! By now you should be familiar with it. Everybody learned to hate it as it is difficult to read, to debug, to change, it keeps getting deeper and deeper in the indentation as you nest more asynchronous operations, the error handling keeps repeating itself, and so on.</p><p>We could have used the famous <a href="http://caolan.github.io/async/"><strong>async</strong></a> library to clean up the code a bit and it would be much shorter, as the error handling is at least in a single place but there would be too much overhead yet:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3456a9964fb5cbdb73b84e34342c63e8/href">https://medium.com/media/3456a9964fb5cbdb73b84e34342c63e8/href</a></iframe><p>Feeling better after finishing the refactor, but time will teach us that better was not enough.</p><p>Later, one day, we learned how to use <strong>promises</strong> and thought the world was not evil anymore with us and we felt like refactoring our code one more time and more and more libraries were also moving into the <strong>promises</strong> world.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8558a90bf172f616a60f1f6689597525/href">https://medium.com/media/8558a90bf172f616a60f1f6689597525/href</a></iframe><p>That was much better, much shorter and much cleaner! Still it had some issues, as there were still too much overhead in the form of multiple then() calls, function () {...} blocks and the need of adding multiple return statements all over the place.</p><p>We finally start to hear about ES6, all the new stuff that is coming into JavaScript including the <strong>arrow functions</strong> (and a bit of destructuring just to have some more fun) and decide to give our beautiful code one more chance.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c2571168ecbc7a6188c95b156f387a19/href">https://medium.com/media/c2571168ecbc7a6188c95b156f387a19/href</a></iframe><p>And this is it! That request handler function was clean, easy to read and reason about, easy to change in the case we needed to add, remove or replace something in the pipeline! We were chaining functions one after the other to mutate the data we gathered through different asynchronous operations, did not have to define intermediate variables to hold that state as was now handled in the chain and the error handling was clear and in a single place. Now we were sure we were definitely in the heaven of JavaScript developers! But was that true? Was that filing going to last?</p><h4>And async/await arrives</h4><p>A few months later, <strong>async/await</strong> comes into the scene. It was going to get into ES7, then postponed, but as <a href="http://babeljs.io/">Babel</a> started to be adopted everywhere, we jumped into the train. We learned we can mark a function as <strong>async</strong> and that keyword will allow us to use <strong>await</strong> inside the function to “halt” the execution flow until the awaited promise settles to make our code look like synchronous again. We also learned the <strong>async</strong> function will always return a promise and we can use <strong>try/catch</strong> blocks again to handle our errors.</p><p>Not too convinced of the benefits, we give our code a new chance and go for a final refactor.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/cefed233fa15fb938e5d2a6e5d89fe12/href">https://medium.com/media/cefed233fa15fb938e5d2a6e5d89fe12/href</a></iframe><p>And now the code looked like plain old imperative synchronous code back again. Soon, we started to feel confident writing code like that as we implemented it in one place after the other and life continues as usual.</p><p>But something deep in your head, tells you something is not 100% OK…</p><h4>The functional programming paradigm</h4><p>Although <strong>functional programming</strong> has been around for more than 30/40 years now, it looks like only recently it is gaining momentum and more and more books, talks, videos, and all kind of software-development-related media is taking care of it. It looks like only recently, we all are starting to understand the benefits of the functional approach to think and develop a program, faster, easier and with higher quality.</p><p>And, of course, as we are curious as hell, we all start learning some of its principles. We acquire new words for our day-to-day vocabulary as <strong>functors</strong>, <strong>monads</strong>, <strong>monoids</strong>, <strong>aplicatives</strong>, and our dev-friends start thinking we are awesome again because we say those strange words quite often!</p><p>And as we continue diving the functional programming paradigm, we start realizing there is real value in there. Those functional programming advocates were not just crazy people. They were possibly right!</p><p>We understand the benefits of immutability, to not store or mutate state, to create complex logic by combining/composing simple functions, to avoid managing loops and let the magic be done by the language interpreter itself so we can focus on what really matters, to even replace conditional branching and error handling by just combining more functions. And this is when functional programming gets you crazy, you have that “aha moment” and nothing is never as it was before!!!</p><p>But… wait a minute!!!</p><p>As we continue happily writing code with <strong>async/await</strong> we realize we have seen all those functional patterns in the past. Did we? Sure! We remember how we used promises and how we chained functional transformations one after the other, without the need to manage state or to branch our code or manage errors in an imperative way. We were already using the Promise <strong>monad</strong> in the past with all the associated benefits but we didn’t know that word by that time!</p><p>And we suddenly realize why the code based on <strong>async/await</strong> was looking weird! We were back writing plain imperative code like in the 80’s, handling errors with <strong>try/catch</strong> blocks like in the 90’s, managing internal state and variables, doing asynchronous operations and writing code that looks like synchronous that suddenly stops and then automagically continues executing as the asynchronous operations complete (cognitive dissonance, perhaps?)…</p><h4>Final thoughts</h4><p>Don’t get me wrong, <strong>async/await</strong> is not the source of all evil in the world. I actually learned to like it after a few months of using it. So, if you feel confortable writing imperative code, learning how to use <strong>async/await</strong> to manage your asynchronous operations might be a good move.</p><p>But if you like <strong>promises</strong> and you like to learn and apply more and more functional programming principles to your code, you might want to just skip <strong>async/await</strong> code entirely, stop thinking imperative and move to this new-old paradigm.</p><p>Happy coding!</p><p>This is the video by <a href="https://medium.com/u/a3129fead82b">Brian Lonsdorf</a> that made me challenge all what I knew about handling asynchronous operations in JavaScript. Take a look at it!</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FSfWR3dKnFIo%3Ffeature%3Doembed&amp;url=http%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DSfWR3dKnFIo&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FSfWR3dKnFIo%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/22929feca00c8f9a56621ba372178966/href">https://medium.com/media/22929feca00c8f9a56621ba372178966/href</a></iframe><p>And, for those willing to read more qualified opinions about async/await being not-so-a-good thing, read <a href="https://medium.com/u/34c0e27619c9">Gorgi Kosev</a>’s great article on the subject:</p><p><a href="https://spion.github.io/posts/es7-async-await-step-in-the-wrong-direction.html">ES7 async functions - a step in the wrong direction</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=95e31263dd31" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[React in 200 bytes?]]></title>
            <link>https://medium.com/@gab_montes/react-in-200-bytes-28156e714165?source=rss-e19f71e319fa------2</link>
            <guid isPermaLink="false">https://medium.com/p/28156e714165</guid>
            <category><![CDATA[react]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[babeljs]]></category>
            <dc:creator><![CDATA[Gabriel Montes]]></dc:creator>
            <pubDate>Sun, 06 Nov 2016 01:14:00 GMT</pubDate>
            <atom:updated>2016-11-06T22:39:02.482Z</atom:updated>
            <cc:license>https://creativecommons.org/publicdomain/mark/1.0/</cc:license>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HAPE9ntItKV0J_KOXc51kQ.png" /><figcaption>It is small but we can still see all its features! (Based on the actual React logo at <a href="https://facebook.github.io/react/">https://facebook.github.io/react/</a>)</figcaption></figure><p>A few weeks ago, I started thinking on creating a small website to show the relationship between Babel presets and plugins after I realized the documentation in the <a href="http://babeljs.io/docs/plugins/">Babel’s site</a> is not always up to date.</p><p>That website should query a server that just parses the presets’ <strong>package.json</strong> files and recursively obtains the related presets. With that information, the web page should render a table. Simple, right?</p><p>The idea was to code the server using Node.JS and as few libraries as possible and the website, that should have a single page, using React. At the end, the objective was having some fun and use the code to teach JavaScript, Node.JS and React in the training courses I usually provide to students and organizations.</p><p>While working on that, I came across the <a href="https://www.youtube.com/watch?v=rI8tNMsozo0">Rails Conf 2012 Keynote, “Simplicity Matters”, by Rich Hickey</a>, and I thought on going one step further. What about trying to redo React in as few lines of code as possible?</p><p>I did exactly that some time ago with jQuery, reimplementing some of its basic and most common functionality during a training course on web applications development. The result of that exercise was <a href="https://gist.github.com/gabmontes/535a7b3b059b2a301a55b43e90ee0101"><strong>not-jquery</strong></a>, a 100-lines file that helped the students understand how to work with the DOM while making jQuery less magical.</p><h4>Reimplementing React</h4><p>In order to start reimplementing React, I needed to set a few restrictions and objectives:</p><ul><li>Support only stateless functional components (no state, life-cycle events)</li><li>Do not use JSX, transpiling, bundling, etc.</li><li>Use no other libraries at all</li><li>Shall work on modern/latest browsers only (no IE)</li><li>Shall be as small as possible (keep only what cannot be taken out)</li></ul><p>So, with that restrictions in place, I started playing around with functions, components and the DOM, from the simplest examples to some more complex use cases. In order to give the development path some order, lets follow some of the examples and cases in the <a href="https://facebook.github.io/react/docs/hello-world.html">React’s Quick Start</a> guides.</p><h4>Hello World</h4><p>Everything in programming starts with a “hello world” example, so this was not the exception. The objective was to make this work:</p><pre>ReactDOM.render(<br>  &lt;h1&gt;Hello, world!&lt;/h1&gt;,<br>  document.getElementById(&#39;root&#39;)<br>)</pre><p>But I said no JSX! And clearly, what I was developing was not <strong>ReactDOM</strong> so I tweaked it a bit:</p><pre>notReactDOM.render(<br>  `&lt;h1&gt;Hello, world!&lt;/h1&gt;`,<br>  document.getElementById(&#39;root&#39;)<br>)</pre><p>Much better! But how to actually render that piece of HTML in the <strong>root</strong> element? It was simpler than I initially thought: just create a <strong>notReactDOM</strong> global object having a `render` method which do the trick.</p><pre>notReactDOM = {<br>  render: function (html, element) {<br>    element.innerHTML = html<br>  }<br>}</pre><p>Simple, very simple!</p><h4>Embedding expressions</h4><p>OK. So far so good. Now it was time to do some magic trying to embed expressions but instead of doing it in the JSX code, in the HTML strings.</p><pre><br>function formatName(user) {<br>  return `${user.firstName} ${user.lastName}`<br>}</pre><pre>const user = {<br>  firstName: &#39;Harper&#39;,<br>  lastName: &#39;Perez&#39;<br>}</pre><pre>const greetingComponent = `<br>  &lt;h1&gt;<br>    Hello, ${formatName(user)}!<br>  &lt;/h1&gt;<br>`</pre><pre>notReactDOM.render(<br>  greetingComponent,<br>  document.getElementById(&#39;root&#39;)<br>)</pre><p>That just worked out of the box. No changes to <strong>notReactDOM.render()</strong> at all! All the magic is in the new <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals">template literals syntax</a>.</p><h4>Functional components</h4><p>But what about inserting some logic, some expressions to change the component content based on the input as when there is no user? Welcome to the functional components:</p><pre>const greetingComponent = function ({ user }) {<br>  if (user) {<br>    return `&lt;h1&gt;Hello, ${formatName(user)}!&lt;/h1&gt;`<br>  }<br>  return &#39;&lt;h1&gt;Hello, Stranger.&lt;/h1&gt;&#39;<br>}</pre><p>In order to render that component, <strong>notReactDOM.render()</strong> had to be changed to manage both strings or functions returning strings.</p><pre>notReactDOM = {<br>  render: function (component, element) {<br>    element.innerHTML = typeof component === &#39;function&#39; ?<br>      component() : <br>      component<br>  }<br>}</pre><p>In addition, the call to <strong>render</strong> that was now expecting a function, should properly inject the initial state to the component:</p><pre>notReactDOM.render(<br>  () =&gt; greetingComponent({ user }),<br>  document.getElementById(&#39;root1&#39;)<br>)</pre><p>It all worked flawlessly!</p><h4>The ticking clock</h4><p>The next challenge was the ticking clock example: render a component and update it once every second.</p><pre>function tick() {<br>  function elementComponent() {<br>    return `<br>      &lt;div&gt;<br>        &lt;h1&gt;Hello, world!&lt;/h1&gt;<br>        &lt;h2&gt;It is ${new Date().toLocaleTimeString()}.&lt;/h2&gt;<br>      &lt;/div&gt;<br>    `<br>  }</pre><pre>notReactDOM.render(<br>    elementComponent,<br>    document.getElementById(&#39;root&#39;)<br>  )<br>}</pre><pre>setInterval(tick, 1000)</pre><p>Did it work? No doubts about it. No changes to our <strong>render</strong> function either.</p><p>Of course in this simple reimplementation of React/ReactDOM, the whole DOM will be updated every tick as opposed to the VitualDOM management React does to improve performance (a lot). But it was just an exercise to understand how it all works and what are the most basic components that can make a React application work. Doing VirtualDOM stuff was completely out of scope. And considering there are a few <a href="https://github.com/Matt-Esch/virtual-dom">libraries that implement the diff/patch algorithms</a>, I moved to the next use case.</p><h4>Composing components</h4><p>Given the components return an HTML string, composing components was straightforward: just call a component within other to obtain the corresponding HTML string.</p><pre>function welcomeComponent({ name }) {<br>  return `&lt;h1&gt;Hello, ${name}&lt;/h1&gt;`<br>}</pre><pre>function appComponent() {<br>  return `<br>    &lt;div&gt;<br>      ${welcomeComponent({ name: &#39;Sara&#39; })}<br>      ${welcomeComponent({ name: &#39;Cahal&#39; })}<br>      ${welcomeComponent({ name: &#39;Edite&#39; })}<br>    &lt;/div&gt;<br>  `<br>}</pre><pre>notReactDOM.render(<br>  appComponent,<br>  document.getElementById(&#39;root&#39;)<br>)</pre><p>Each component is a function and therefore should receive the list of properties needed to customize the rendering. Using the destructuring syntax helps a lot in visualizing the code and making it even more clear.</p><h4>Iterating over lists</h4><p>And what about lists? My original objective was to work over lists of presets and plugins. Remember?</p><p>Using <strong>map</strong> to map arrays to their HTML representations is the key to manage iterations.</p><pre>const numbers = [1, 2, 3, 4, 5]</pre><pre>const listItems = numbers.map(number =&gt; `<br>  &lt;li&gt;${number}&lt;/li&gt;<br>`).join(&#39;&#39;)</pre><pre>notReactDOM.render(<br>  `&lt;ul&gt;${listItems}&lt;/ul&gt;`,<br>  document.getElementById(&#39;root&#39;)<br>)</pre><p>The important thing when mapping lists to HTML strings is to concatenate those strings before passing it up to the parent component with an empty string. Otherwise, JavaScript will convert the arrays to strings by concatenating the elements with a comma.</p><p>What about keys to track what items in the list changed? No VirtualDOM, remember? No need for keys.</p><p>If a VirtualDOM were implemented, the mapping should be done with a helper function to manage both joining the array elements and keys generation.</p><h4>Handling events</h4><p>The last challenge in this series was to handle events, like the click of a button. In JSX that is pretty easy. Defining a <strong>click</strong> property and binding it to a function in the component.</p><p>But in this simple version of React, there was no JSX, and no easy way to bind the event handlers that might be defined inside the components to the resulting HTML that would “live” in the global scope.</p><pre>let state = {<br>  isToggleOn: true<br>}</pre><pre>function setState(newState) {<br>  Object.assign(state, newState)<br>  render()<br>}</pre><pre>function handleClick() {<br>  setState({<br>    isToggleOn: !state.isToggleOn<br>  })<br>}</pre><pre>function toggleComponent({ isToggleOn }) {<br>  return `<br>    &lt;button onclick=&quot;handleClick()&quot;&gt;<br>      ${isToggleOn ? &#39;ON&#39; : &#39;OFF&#39;}<br>    &lt;/button&gt;<br>  `<br>}</pre><pre>function render() {<br>  notReactDOM.render(<br>    () =&gt; toggleComponent(state),<br>    document.getElementById(&#39;root&#39;)<br>  )<br>}</pre><pre>render()</pre><p>The solution was hack-ish, clearly not elegant, but it worked again: using global functions that change the global state of the application. The good part of this solution is that going this path forces the developer to use a single global state and use functions that change that state and trigger a new rendering cycle.</p><p>It had some “redux” smell too. Perhaps the next challenge would be to reimplement is as “not-redux”?</p><h4>Conclusion</h4><p>Reimplementing React was a learning experience for me and for sure will help others to understand there is not magic under the hood but some clever decisions in terms of architecture, data flow and way of thinking the application. At the end, sticking to the initial set of restrictions and taking performance and compatibility aside, the whole code for the library can be summarized as follows:</p><pre>notReactDOM = {<br>  render: function (component, element) {<br>    element.innerHTML = typeof component === &#39;function&#39; ?<br>      component() : <br>      component<br>    }<br>}</pre><p>And that is less than 200-bytes long!!</p><h4>Some resources</h4><ul><li><strong>not-react</strong> experimentation repo:<br><a href="https://github.com/gabmontes/exploring-not-react">https://github.com/gabmontes/exploring-not-react</a></li><li>Babel preset to plugins website:<br><a href="https://babel-presets.utoctadel.com.ar/">https://babel-presets.utoctadel.com.ar/</a></li><li>Server and app code for the website:<br><a href="https://github.com/gabmontes/babel-preset-to-plugins">https://github.com/gabmontes/babel-preset-to-plugins</a></li></ul><p>Originally published on my blog: <a href="https://blog.utoctadel.com.ar/2016/11/05/react-in-200-bytes.html">https://blog.utoctadel.com.ar/2016/11/05/react-in-200-bytes.html</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=28156e714165" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>