<?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 Fernando Cañas on Medium]]></title>
        <description><![CDATA[Stories by Fernando Cañas on Medium]]></description>
        <link>https://medium.com/@wfercanas?source=rss-f521f4b6977e------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*2zZ4pFK65vap1fqbvXtGtg.jpeg</url>
            <title>Stories by Fernando Cañas on Medium</title>
            <link>https://medium.com/@wfercanas?source=rss-f521f4b6977e------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 16:07:37 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@wfercanas/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[Slow Array.includes() vs. Fast Object.hasOwnProperty()]]></title>
            <link>https://medium.com/@wfercanas/slow-array-includes-vs-fast-object-hasownproperty-662496f95089?source=rss-f521f4b6977e------2</link>
            <guid isPermaLink="false">https://medium.com/p/662496f95089</guid>
            <category><![CDATA[search]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[frontend]]></category>
            <category><![CDATA[algorithms]]></category>
            <category><![CDATA[backend]]></category>
            <dc:creator><![CDATA[Fernando Cañas]]></dc:creator>
            <pubDate>Sat, 29 Mar 2025 17:39:26 GMT</pubDate>
            <atom:updated>2025-03-29T17:39:26.828Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*r_cTJI4vqRKvAnbE" /><figcaption>Photo by <a href="https://unsplash.com/@sulyok_imaging?utm_source=medium&amp;utm_medium=referral">Adrian Sulyok</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Let’s say we have a list of items that belong to our shop inventory. Our shop is huge, so is the list of items we sell.</p><p>As the list becomes larger, the task of finding an item tends to take more time. But, the time per search increases the same amount regardless of how we store the items?</p><p>In a physical environment, some warehouses could be better organized than others, so we can guess that the time increase for searching an object in a well organized warehouse is lower than the increase in a warehouse where things are just anywhere.</p><p>So may be the case in a digital environment.</p><p>Let’s see this problem in two different situations: a list of items stored in an array, where we’ll use the Array.includes() method to find some of them and a list of items stored in an object where we’ll use the Object.hasOwnProperty() method to find some items as well.</p><h3>Creating items</h3><p>First, we need to create some items to run our experiment. To keep it simple we will work only with SKU (stock-keeping units) that are formed with lengths between 8 and 12 characters.</p><p>Let’s create a function to get a random character in an ASCII range:</p><pre>function randomChar() {<br>  return String.fromCharCode(Math.floor(Math.random() * 26) + 65);<br>}</pre><p>And now a function to create a random SKUs:</p><pre>function randomSKU() {<br>  let sku = &quot;&quot;;<br>  const randomLength = Math.floor(Math.random() * 4) + 8;<br><br>  for (let i = 0; i &lt; randomLength; i++) {<br>    sku = sku + randomChar();<br>  }<br><br>  return sku;<br>}</pre><p>To make it simple, our SKUs won’t be alphanumeric. They’re just alphabetic.</p><p>Now we can create as manu SKUs as we want.</p><h3>Items to search</h3><p>We can create a million SKUs, but when we run our experiment that is not enough. We need a list of items to search within that set of million SKUs.</p><p>We can take advantage of the process of creating SKUs, so we can also include some of them into our list of searchable items while the process is running.</p><h4>Callback extension</h4><p>To avoid that the process of creating SKUs has to know about some searchable items list or whatever, we can just extend our SKUs generator function to receive a callback. Like this, we can pass a function, any function, to make any kind of operation with the SKUs just created.</p><pre>function randomSKU(callback) {<br>  let sku = &quot;&quot;;<br>  const randomLength = Math.floor(Math.random() * 4) + 8;<br><br>  for (let i = 0; i &lt; randomLength; i++) {<br>    sku = sku + randomChar();<br>  }<br><br>  callback(sku);<br>  return sku;<br>}</pre><h4>Add items to lookup list</h4><p>We’ll store the list of items (SKUs) to search in an array. The process of adding items to it has two rules:</p><ol><li>This list length should be around 5% of the length of the full list of SKUs.</li><li>This list should have around 20% of items that may not be found in the list of SKUs.</li></ol><p>These rules are just to control the experiment and allow some scenarios where the search returns that an item wasn’t found.</p><p>With this in mind, let’s create the function that we’ll then pass as a callback into our SKUs generator:</p><pre>const lookupItems = [];<br>function addLookupItem(sku) {<br>  // Controls that we only add around 5% of SKUs.<br>  const lookable = Math.random() &lt; 0.05;<br>  if (!lookable) {<br>    return;<br>  }<br><br>  let newSku = sku;<br><br>  /* Adds an special character we know is not part of an SKU to ensure <br>  that the item will not be found in the list of SKUs.<br>  */<br>  const noisable = Math.random() &lt; 0.2;<br>  if (noisable) {<br>    newSku = newSku + &quot;*&quot;;<br>  }<br><br>  /* Here we&#39;ll make use of includes to avoid adding duplicates.<br>    This code is just for preparing the execution of the experiment<br>    and will be used by both the includes() and hasOwnProperty() runs.<br>  */<br>  if (!lookupItems.includes(newSku)) {<br>    lookupItems.push(newSku);<br>  }<br>}</pre><p>The <em>lookupItems</em> array is declared in the outer scope so we can access it from different places of the experiment.</p><h3>Timer</h3><p>Now we can create a list of SKUs as large as we want it to be, while we create as well the list of items to be searched.</p><p>This is just the foundation of the experiment, but we’re missing one part. We need to know how long does it take to complete the task of searching the whole <em>lookupItems</em> list.</p><p>For this, we’ll create a timer function:</p><pre>function timer(processName) {<br>  const start = new Date();<br><br>  setTimeout(() =&gt; {<br>    const end = new Date();<br>    console.log(processName, end - start, &quot;ms&quot;);<br>  }, 0);<br>}</pre><h3>Ready to roll</h3><p>Now we’re ready! To make it fair, lets work in both scnearios with 1.000.000 SKUs</p><h4>Array.includes()</h4><p>Let’s create the run for the array execution and see how long it takes:</p><pre>// -----------------------------Arrays<br><br>const arrayItems = [];<br>for (let i = 0; i &lt; 1000000; i++) {<br>  const item = randomSKU(addLookupItem);<br>  arrayItems.push(item);<br>}<br><br>function arraySearch() {<br>  timer(&quot;array&quot;);<br>  for (let item of lookupItems) {<br>    arrayItems.includes(item);<br>  }<br>}<br><br>arraySearch();</pre><p>It will take a while….</p><p>But, eventually it will end! In my PC, the result is ~<strong>74000ms</strong>. In yours it may be different, take note of it.</p><h4>Object.hasOwnProperty()</h4><pre>// --------------------------------Objects<br><br>const objectItems = {};<br>for (let i = 0; i &lt; 1000000; i++) {<br>  const item = randomSKU(addLookupItem);<br>  objectItems[item] = item;<br>}<br><br>function objectSearch() {<br>  timer(&quot;object&quot;);<br>  for (let item of lookupItems) {<br>    objectItems.hasOwnProperty(item);<br>  }<br>}<br><br>objectSearch();</pre><p>This is fast!</p><p>In my PC, the result is <strong>~7ms</strong>. With this kind of difference, you may get different values, but the conclusion should be the same.</p><h3>Result</h3><p>See that the timer starts when the search operations begin, so it does not include the preparation phase of the experiment.</p><p>The difference is 74000/7 ~= 10000 (10K!).</p><p>10K = 10⁴, which can also be stated as four magnitude orders.</p><h3>Rabbit hole</h3><p>The aim of this article is not academic. But let’s validate our intuition.</p><p>If you have to search an SKU in a warehouse with a million SKUs, and the only way you have to complete that search is to go to the floor and look item by item, we can surely call that a sh*t job.</p><p><em>Notice I use interchangably the words item and SKU because I’m assuming we have only one item per SKU, the problem could be worse if the relation is greater than one.</em></p><p>But, if you have an index of all the SKUs your warehouse stores, you can just go check that index instead of going to the floor.</p><p>If you want to go into the rabbit hole, check these resources:</p><ul><li><a href="https://en.wikipedia.org/wiki/Hash_table">https://en.wikipedia.org/wiki/Hash_table</a></li><li><a href="https://www.freecodecamp.org/news/data-structures-in-javascript-with-examples/">https://www.freecodecamp.org/news/data-structures-in-javascript-with-examples/</a></li><li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Keyed_collections">https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Keyed_collections</a></li><li><a href="https://www.freecodecamp.org/news/javascript-hash-table-associative-array-hashing-in-js/">https://www.freecodecamp.org/news/javascript-hash-table-associative-array-hashing-in-js/</a></li></ul><h3>Conclusions</h3><p>Not all warehouses are the same, as not all programs are the same.</p><p>When considering performance, we can approach optimization typically by:</p><ol><li>Improving the algorithm we’re using.</li><li>Changing the data structures we’re using.</li><li>Implementing multi-threading to move slow operations to a separate thread.</li><li>Adding more resources to the computing device.</li></ol><p>In this experiment we can see one of the items displayed above in action. Changing the data sctructure provided a huge improvement in the program performance, perhaps preventing us from implementing more costly solutions like adding computer resources (monetary cost) or increasing complexity by working with multi-threading (mental cost).</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=662496f95089" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[What are transpilers and polyfills in Javascript]]></title>
            <link>https://medium.com/@wfercanas/what-are-transpilers-and-polyfills-in-javascript-967b538037dc?source=rss-f521f4b6977e------2</link>
            <guid isPermaLink="false">https://medium.com/p/967b538037dc</guid>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[backend]]></category>
            <category><![CDATA[front-end-development]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Fernando Cañas]]></dc:creator>
            <pubDate>Sun, 12 May 2024 16:02:56 GMT</pubDate>
            <atom:updated>2024-05-12T16:02:56.916Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*btqBnYjaJ0Juhhs_" /><figcaption>Photo by <a href="https://unsplash.com/@aleksandr_barsukov?utm_source=medium&amp;utm_medium=referral">Aleksandr Barsukov</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>When working with JavaScript, two concepts will come your way sooner or later: transpile and polyfill. This article is about placing those two concepts in context, why do they exist and how they operate.</p><p>There are three pieces in the puzzle that explain why we have to deal with transpilation and creation of polyfills. Let’s see each one of them.</p><h3><strong>Puzzle pieces</strong></h3><h4><strong>JavaScript releases</strong></h4><p><strong>JavaScript is a language that is improving regularly</strong>. This process is handled by <a href="https://ecma-international.org/">ECMA International</a>, an organization dedicated to standardization of information and communication systems and who has the responsibility of controlling the future of ECMAScript — or JavaScript as we know it — .</p><p>If we look at the language history, we can see a series of new releases through the years. Just looking at the years where ECMA is the releaser we have multiple <a href="https://ecma-international.org/publications-and-standards/standards/ecma-262/">editions</a>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/962/1*4lfAPBrIShTNfpadH3O4Cw.png" /><figcaption>Timeline with ECMAScript editions</figcaption></figure><p>These variations to the language specification constitute the first piece of the puzzle.</p><h4><strong>The promise</strong></h4><p>These releases embody a fundamental promise, one that will define what we can expect from any change that is accepted as valid JavaScript in any release: <strong>no change in the language will be accepted if that change deprecates or makes invalid a part of the language that once was valid JavaScript.</strong></p><p>This is known as backwards compatibility and to make a promise like this is not a small thing. If we, today, decide to write JavaScript as we used to when we were working with the 1st Edition of the ECMA specification, that JavaScript is still valid today. There may be very very special situations in which some features of the language are not valid today, but that is also noted in the specification and apply for long studied corner cases.</p><p>This promise is the second piece of the puzzle.</p><h4><strong>The environment isn’t yours</strong></h4><p>JavaScript’s destiny is connected to the Web’s destiny. They are intertwined and will continue like that for many years to come. That connection materializes through browsers.</p><p>Browsers are our doors to the Web and are software that we as developers or software companies can’t control. They are variables given to us and we must learn to deal with them on a daily basis.</p><p>There are just a bunch of companies that develop the browsers we use, and each one has their own roadmap about how to make their products evolve over time. In that roadmap is included how the browser will conform to the JavaScript specification — e.g. how to implement what is necessary in the browser to support JavaScript — .</p><p>Since a huge part of the code we write in JavaScript will end up running in a browser we don’t own, we end up with a major challenge to solve. <strong>How to make our code run properly in those foreign environments</strong>.</p><p>This is the third piece of the puzzle.</p><h3><strong>A Browser trapped in time</strong></h3><p>Let’s use the pieces to see the whole picture. Let’s say that we have installed in our computer a browser and that we haven’t update it since the day we installed it.</p><p>If that installation happened in 2013, our browser will look like this in our timeline:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/962/1*Hy__CJIKHqQtSzS30VcSkw.png" /><figcaption>Browser installed in 2013</figcaption></figure><h4><strong>Backwards compatibility</strong></h4><p>As stated before, if all the JavaScript code that our good old browser tries to run was created following the standards prior to 2013, we will have no problem at all.</p><p>The promise piece assures us that all JavaScript code that was valid, remains valid over time. So, if our browser supports the standard version 5.1, we can implement all our features with JavaScript in that version or prior and everything should be ok.</p><h4><strong>Forwards compatibility</strong></h4><p>Here is where issues appear. The promise doesn’t cover the future. In our example, the promise doesn’t cover our good old browser from having problems trying to execute JavaScript code that is valid in 2015, 2016, etc. — those standards are the future related to our 2013 browser — .</p><p>We can form two groups of problems when attempting to run that code in our browser: syntax problems and API problems.</p><h4><strong>Syntax problems</strong></h4><p>You will find in the JavaScript jargon the expression: ES6. That expression is related to the 6th edition of the ECMAScript standard, the one you can see in 2015 in out timeline graph.</p><p>That version of the specification released multiple new features, one of them being the famous <strong>arrow functions</strong>.</p><pre>// Declaring functions prior ES6<br>function helloWorld() {}<br>// Assigning functions prior ES6<br>var helloWorld = function () {};<br>// Assigning an arrow function (ES6)<br>const helloWorld = () =&gt; {};<br>// This is an arrow function<br>() =&gt; {};</pre><p>If we try to use our helloWorld arrow function in the 2013 browser we will get a syntax error. When the browser is trying to execute our code, the expression of the function is something the browser cannot recognize, so it doesn’t know what to do with it.</p><p>For now, let’s just include in our diagram this situation before explaining how to deal with it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/962/1*Kue4NfuC9TcMX8AOyNB5cg.png" /><figcaption>SyntaxError for using Arrow Functions (ES6)</figcaption></figure><h4><strong>API problems</strong></h4><p>These problems happen not because the browser doesn’t understand the code, the syntax is correct. They happen because we’re trying to use functionality that the environment doesn’t support.</p><p>Methods like <em>document.getElementById()</em> or functions like <em>setTimeout()</em> need to be part of the environment in which you are running your code. If those functionalities are not present, trying to run them will break the program.</p><p>For the upcoming 2024 ES release, a new method will be published for the Object class: <em>Object.groupBy()</em>. This method will allow you to pass an iterable, iterate over all its items and form groups with them. You can get a list of numbers and group the odd ones and the even ones, get a list of letters and group the vowels and the consonants or get the list of products in your ecommerce and group the references of shirts, shoes, trousers, and joggers.</p><p>If we try to group words by length, and use the <em>Object.groupBy()</em> method in an environment that supports the method, we will get something like this:</p><pre>const words = [<br>&quot;hello&quot;,<br>&quot;sun&quot;,<br>&quot;flow&quot;,<br>&quot;ant&quot;,<br>&quot;mic&quot;,<br>&quot;fever&quot;,<br>&quot;mega&quot;,<br>&quot;looks&quot;,<br>&quot;finds&quot;,<br>&quot;reads&quot;,<br>&quot;init&quot;,<br>&quot;mark&quot;,<br>&quot;december&quot;,<br>];<br>console.log(Object.groupBy(words, (item) =&gt; item.length));</pre><pre>[Object: null prototype] {<br>&#39;3&#39;: [ &#39;sun&#39;, &#39;ant&#39;, &#39;mic&#39; ],<br>&#39;4&#39;: [ &#39;flow&#39;, &#39;mega&#39;, &#39;init&#39;, &#39;mark&#39; ],<br>&#39;5&#39;: [ &#39;hello&#39;, &#39;fever&#39;, &#39;looks&#39;, &#39;finds&#39;, &#39;reads&#39; ],<br>&#39;8&#39;: [ &#39;december&#39; ]<br>}</pre><p>If we try to run the same code in an environment that doesn’t support the method (like our 2013 Browser), we will get something like this:</p><pre>/home/groupByLength.js:28<br>console.log(Object.groupBy(words, (item) =&gt; item.length));<br>^<br>TypeError: Object.groupBy is not a function<br>at Object.&lt;anonymous&gt; (/home/groupByLength.js:28:20)<br>at Module._compile (internal/modules/cjs/loader.js:1114:14)<br>at Object.Module._extensions..js (internal/modules/cjs/loader.js:1143:10)<br>at Module.load (internal/modules/cjs/loader.js:979:32)<br>at Function.Module._load (internal/modules/cjs/loader.js:819:12)<br>at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:75:12)<br>at internal/main/run_main_module.js:17:47</pre><p>As you can see, we have now a problem because we’re trying to run a functionality that is not supported in the environment we’re using.</p><p><em>If you want to learn more about this method you can see the article I published recently about how to use it </em><a href="https://www.wfercanas.com/article/how-to-group-items-from-an-iterable-in-javascript"><em>here</em></a><em>.</em></p><p>Let’s add this problem to our timeline:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/980/1*gVNxFDHL5iCYEF49qlJWpg.png" /><figcaption>TypeError for trying to use Object.groupby()</figcaption></figure><p><strong>With these elements settled, we’re ready to talk about transpilers and polyfills</strong></p><h3><strong>Transpilers</strong></h3><p>Transpile is a verb that the dev community invented to talk about taking some come and convert it in an equivalent form so that it can be properly executed in a different environment. Equivalent because the functionality of the code should remain intact, the outcome of the program should remain still.</p><p>This is helpful for us in the scenarios in which we have SyntaxErrors, because our environment doesn’t know how to read the program we’re running. So, the idea here is that we can transform (transpile) our program to an equivalent version of it that our environment (target environment) can understand.</p><p>A huge player in this context is <a href="https://babeljs.io/">Babel</a>, whose transpiler is widely used in multiple apps to achieve this very result.</p><p>Let’s see how does <a href="https://babeljs.io/repl">Babel transpiler</a> helps us to solve the situation in which our code uses arrow functions, <em>const</em> variables, object destructuring and string interpolation (features not available in our old browser, which we will set as firefox v30):</p><p>Our code:</p><pre>const player = {<br>name: &quot;Michael&quot;,<br>city: &quot;Miami&quot;,<br>};<br>const greet = ({ name, city }) =&gt; {<br>console.log(`Hello ${name} from ${city}`);<br>};<br>greet(player);</pre><p>Babel transpilation:</p><pre>var player = {<br>name: &quot;Michael&quot;,<br>city: &quot;Miami&quot;,<br>};<br>var greet = function greet(_ref) {<br>var name = _ref.name,<br>city = _ref.city;<br>console.log(&quot;Hello &quot;.concat(name, &quot; from &quot;).concat(city));<br>};<br>greet(player);</pre><p>As you can see, Babel changes the structure of the program but not its functionality. It still works as intended, but the language features we’re using now are included in old JavaScript.</p><p>Here we’re:</p><p>1. Using <em>var</em> definitions, not const — nor let — .</p><p>2. Getting an object as a parameter and then creating variables using the object properties for initialization, not destructuring.</p><p>3. Using the method <em>concat()</em> of Strings to print our greeting, not using string interpolation.</p><p><strong>So, our transpiler requires the code to transpile and the target — environment — where we intend to run our code as basic parameters and with that it creates an equivalent version of our program using the syntax our target can understand.**</strong></p><h3><strong>Polyfills</strong></h3><p>We saw that when we try to run a method like <em>Object.groupBy()</em> in an environment that doesn’t support it, we will get a TypeError. So, the solution for this problem is to provide our environment with the code required to make the program work. This means, that if the environment doesn’t know our method, we will make it know it.</p><p>Polyfills are then that code. One that ideally follows the ECMAScript specification for our functionality and that we can inject into our environment so we can work as if it were an updated one.</p><p>Typically, when using a polyfill, we ask first if the functionality exists or not, because if it does we don’t want to replace the environment’s native functionalities for our own. It it doesn’t exist, we can use our own.</p><p>This is how the polyfill for Object.groupBy() may look like — this is an educational piece of code, not one that you should use in production — :</p><pre>if (!Object.groupBy) {<br>  Object.groupBy = function (iterable, callback) {<br>  const groups = {};<br>  for (let item of iterable) {<br>    const result = callback(item);<br>    if (!groups[result]) {<br>      groups[result] = [item];<br>    } else {<br>      groups[result].push(item);<br>    }<br>  }<br>  return groups;<br>  };<br>}</pre><p><strong>With this addition, we can now use </strong><em>Object.groupBy()</em><strong>. We can then do the same with any modern API in the language that our target environment doesn’t support.</strong></p><h3><strong>Final Remarks</strong></h3><p>Three fundamental pieces explain why we need transpiling and polyfills in JavaScript:</p><p>1. The language is evolving, creating a gap where up-to-date JavaScript may not be supported by certain target environment (yet).</p><p>2. The language is backwards-compatible but not forwards-compatible, so future syntax or functionalities of the language don’t have to be supported by old environments.</p><p>3. You don’t control the environments, you just have to deal with them.</p><p>In this context, we can end up in a situation where we’re attempting to run modern JavaScript code but get SyntaxErrors or TypeErrors. Each one of them has one solution:</p><p>1. <strong>Transpiling</strong>: take your code and convert it into an equivalent form that an old environment can understand. The way the program is written changes, but the results of it while running remain intact. Babel is a key companion here.</p><p>2. <strong>Polyfill</strong>: ask your environment if it knows/supports a new functionality/api. If it does, you can go on and run your code without problems. If it doesn’t, then we need to inform our environment what it is supposed to do when we attempt to run that functionality. Polyfills are then the code that run instead of a built-in functionality of our environment. The advice is that you get your polyfills from libraries that follow the ECMAScript standards.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=967b538037dc" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Group items with new Object.groupBy() JavaScript method]]></title>
            <link>https://medium.com/@wfercanas/how-to-group-items-from-an-iterable-in-javascript-0c2fd5101719?source=rss-f521f4b6977e------2</link>
            <guid isPermaLink="false">https://medium.com/p/0c2fd5101719</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[front-end-development]]></category>
            <dc:creator><![CDATA[Fernando Cañas]]></dc:creator>
            <pubDate>Sat, 24 Feb 2024 17:20:36 GMT</pubDate>
            <atom:updated>2024-02-26T20:59:23.218Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*PvT9Wok7GNN1T8DJ" /><figcaption>Photo by <a href="https://unsplash.com/@mourimoto?utm_source=medium&amp;utm_medium=referral">Mourizal Zativa</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>We often have an iterable data structure that contains a whole bunch of items that we would like to accomodate in different groups depending on some operation or property.</p><p>This article presents how we would do it manually, test our implementation and compare it with a new addition to JavaScript: <em>Object.groupBy()</em>. This static method of the Object class will simplify how we can achieve the same results.</p><h3><strong>Group numbers</strong></h3><p>Let’s say we have a list of numbers and we need to create two groups with them: one with all the odd numbers in the list and a second one with all the even numbers.</p><p><strong>Our mission is to build a custom groupBy function to perform this grouping</strong>, along with a test function to check that everything is ok. Given a list of 5 numbers, this is how the transformation should look like:</p><pre>const numbers = [1, 2, 3, 4, 5]; // -&gt; {odd: [1, 3, 5], even: [2, 4]}jav</pre><h4><strong>Even vs Odd</strong></h4><p>Let’s start by defining how we can evaluate if a given number is even or odd. With this function, we will be able to test any number and decide in which group it should be inserted.</p><pre>function evenOrOdd(number) {<br>  if (number % 2 === 0) {<br>    return &quot;even&quot;;<br>  }<br>    return &quot;odd&quot;;<br>  }</pre><p>The function checks if the remainder of a division by 2 is equal to zero, in which case the number is even and the function returns “<strong>even”</strong>. On the contrary, the function returns “<strong>odd”</strong>.</p><p>Let’s simplify a bit:</p><pre>function evenOrOdd(number) {<br>  return number % 2 === 0 ? &quot;even&quot; : &quot;odd&quot;;<br>}</pre><h4><strong>Implementation</strong></h4><p>With the aid of our <em>evenOrOdd</em> function, we can continue creating a function to make the grouping work. Let’s begin with a function that works only for our current scenario:</p><pre>function groupBy(numbers) {<br>  const groups = {};<br>  for (let number of numbers) {<br>    const result = evenOrOdd(number);<br>    if (!groups[result]) {<br>      groups[result] = [number];<br>    } else {<br>      groups[result].push(number);<br>    }<br>  }<br>  return groups;<br>}</pre><h4><strong>Test function</strong></h4><p>We can use the function directly and log the results to see if everything works as intended. But let’s create a test function to organize the execution of the function and improve the readibility of the outcomes.</p><p>Our test function has access to groupBy because they are defined in the same scope.</p><pre>function testGroupBy(numbers, expected) {<br>  let test = &quot;Passed&quot;;<br>  const groups = groupBy(numbers);<br>  <br>  const result = {<br>    test,<br>    result: JSON.stringify(groups),<br>    expected: JSON.stringify(expected),<br>  };<br><br>  const groupsKeys = Object.keys(groups);<br>  const expectedKeys = Object.keys(expected);<br><br>  if (groupsKeys.length !== expectedKeys.length) {<br>    test = &quot;Failed&quot;;<br>    return result;<br>  }<br><br>  for (let key of groupsKeys) {<br>    if (!expectedKeys.includes(key)) {<br>      test = &quot;Failed&quot;;<br>      return result;<br>    }<br>    if (groups[key] !== expected[key]) {<br>      test = &quot;Failed&quot;;<br>      return result;<br>    }<br>  }<br>  return result;<br>}</pre><p>Good. Let’s create then a set of test scenarios and run them:</p><pre>const naturals = [1, 2, 3, 4, 5];<br>const odds = [1, 3, 5, 7];<br>const evens = [2, 4, 6, 8];<br>const empty = [];<br><br>console.table([<br>  testGroupBy(naturals, { odd: [1, 3, 5], even: [2, 4] }),<br>  testGroupBy(odds, { odd: [1, 3, 5, 7] }),<br>  testGroupBy(evens, { even: [2, 4, 6, 8] }),<br>  testGroupBy(empty, {}),<br>]);</pre><p>Results:</p><pre>┌─────────┬──────────┬────────────────────────────────┐<br>│ (index) │ test     │ result                         │<br>├─────────┼──────────┼────────────────────────────────┤<br>│ 0       │ &#39;Passed&#39; │ &#39;{&quot;odd&quot;:[1,3,5],&quot;even&quot;:[2,4]}&#39; │<br>│ 1       │ &#39;Passed&#39; │ &#39;{&quot;odd&quot;:[1,3,5,7]}&#39;            │<br>│ 2       │ &#39;Passed&#39; │ &#39;{&quot;even&quot;:[2,4,6,8]}&#39;           │<br>│ 3       │ &#39;Passed&#39; │ &#39;{}&#39;                           │<br>└─────────┴──────────┴────────────────────────────────┘</pre><h4><strong>More scenarios</strong></h4><p>Our implementation seems to work just fine, but only for the scenario in which we’re grouping numbers into odd and even groups. In the next section we will refactor our implementation to make it work in more scenarios.</p><h3><strong>Group letters</strong></h3><p>Let’s imagine now that we don’t need to group a list of numbers in terms of odd or even numbers, but that we must group a list of letters in two groups: vowels and consonants. Sadly, our implementation as it is right now is far from working in this new scenario.</p><p>So, we have to check how to extend our implementation so we can create a more useful <strong>groupBy</strong> function. If we analyze our code, we can see that we’re currently expecting a list of numbers as a parameter and assume that we can iterate over that list to check if each number is odd or not.</p><p>Let’s see how we can make some adjustments to create a more general <strong>groupBy</strong> function.</p><h4><strong>Refactoring</strong></h4><p>We can refactor our function to:</p><p>1. Don’t expect just numbers, but a list of items.</p><p>2. Since we’re going to use a for..of bucle, we’re assuming that the list is iterable. So we can rename the parameter to <strong>iterable</strong>.</p><p>3. We have the function that returns the group an item belongs to inside our <strong>groupBy</strong> implementation, we can change this and instead receive the function through parameters. Let’s call this parameter <strong>callback</strong>.</p><pre>function groupBy(iterable, callback) {<br>  const groups = {};<br>  for (let item of iterable) {<br>    const result = callback(item);<br>    if (!groups[result]) {<br>      groups[result] = [item];<br>    } else {<br>      groups[result].push(item);<br>    }<br>  }<br>  return groups;</pre><p>With this change our program will throw a <strong>TypeError</strong> if we try to execute it, because when testing our function we’re not using the callback property. So, we must refactor the test function as well:</p><pre>function testGroupBy(iterable, callback, expected) {<br>  let test = &quot;Passed&quot;;<br>  const groups = groupBy(iterable, callback);<br><br>  /*<br>    Same code as before ...<br>  */<br>}</pre><p>Finally, let’s change our test executions:</p><pre>console.table([<br>  testGroupBy(naturals, oddOrEven, { odd: [1, 3, 5], even: [2, 4] }),<br>  testGroupBy(odds, oddOrEven, { odd: [1, 3, 5, 7] }),<br>  testGroupBy(evens, oddOrEven, { even: [2, 4, 6, 8] }),<br>  testGroupBy(empty, oddOrEven, {}),<br>]);</pre><h4><strong>Callback for grouping letters</strong></h4><p>With our refactor in place, we can now focus in our new scenario. Let’s create a function that check if a letter is a vowel or a consonant.</p><pre>function vowelOrConsonant(letter) {<br>  const vowels = &quot;aeiou&quot;;<br>  const consonants = &quot;bcdfghjklmnpqrstvwxyz&quot;;<br><br>  if (vowels.includes(letter)) {<br>    return &quot;vowels&quot;;<br>  }<br><br>  if (consonants.includes(letter)) {<br>    return &quot;consonants&quot;;<br>  }<br>}</pre><h4><strong>Test cases for letters</strong></h4><p>Good. We can now write some test cases and run them to check if our refactored implementation can handle this new situation:</p><pre>const hello = [&quot;h&quot;, &quot;e&quot;, &quot;l&quot;, &quot;l&quot;, &quot;o&quot;];<br>const vowels = [&quot;a&quot;, &quot;a&quot;, &quot;e&quot;, &quot;o&quot;];<br>const consonants = [&quot;w&quot;, &quot;r&quot;, &quot;l&quot;, &quot;d&quot;, &quot;d&quot;];<br>const numbers = [1, 2, 3];<br>const greet = &quot;helloworld&quot;;<br><br>console.table([<br>  testGroupBy(hello, vowelOrConsonant, {<br>    vowels: [&quot;e&quot;, &quot;o&quot;],<br>    consonants: [&quot;h&quot;, &quot;l&quot;, &quot;l&quot;],<br>  }),<br>  testGroupBy(vowels, vowelOrConsonant, {<br>    vowels: [&quot;a&quot;, &quot;a&quot;, &quot;e&quot;, &quot;o&quot;],<br>  }),<br>  testGroupBy(consonants, vowelOrConsonant, {<br>    consonants: [&quot;w&quot;, &quot;r&quot;, &quot;d&quot;, &quot;d&quot;],<br>  }),<br>  testGroupBy(numbers, vowelOrConsonant, {}),<br>  testGroupBy(greet, vowelOrConsonant, {<br>    vowels: [&quot;e&quot;, &quot;o&quot;, &quot;o&quot;],<br>    consonants: [&quot;h&quot;, &quot;l&quot;, &quot;l&quot;, &quot;w&quot;, &quot;r&quot;, &quot;l&quot;, &quot;d&quot;],<br>  }),<br>]);</pre><pre>┌─────────┬──────────┬───────────────────────────────────────────────────────────────────────┐<br>│ (index) │ test     │ result                                                                │<br>├─────────┼──────────┼───────────────────────────────────────────────────────────────────────┤<br>│ 0       │ &#39;Passed&#39; │ &#39;{&quot;consonants&quot;:[&quot;h&quot;,&quot;l&quot;,&quot;l&quot;],&quot;vowels&quot;:[&quot;e&quot;,&quot;o&quot;]}&#39;                     │<br>│ 1       │ &#39;Passed&#39; │ &#39;{&quot;vowels&quot;:[&quot;a&quot;,&quot;a&quot;,&quot;e&quot;,&quot;o&quot;]}&#39;                                        │<br>│ 2       │ &#39;Passed&#39; │ &#39;{&quot;consonants&quot;:[&quot;w&quot;,&quot;r&quot;,&quot;l&quot;,&quot;d&quot;,&quot;d&quot;]}&#39;                                │<br>│ 3       │ &#39;Passed&#39; │ &#39;{&quot;undefined&quot;:[1,2,3]}&#39;                                               │<br>│ 4       │ &#39;Passed&#39; │ &#39;{&quot;consonants&quot;:[&quot;h&quot;,&quot;l&quot;,&quot;l&quot;,&quot;w&quot;,&quot;r&quot;,&quot;l&quot;,&quot;d&quot;],&quot;vowels&quot;:[&quot;e&quot;,&quot;o&quot;,&quot;o&quot;]}&#39; │<br>└─────────┴──────────┴───────────────────────────────────────────────────────────────────────┘</pre><p>Everything seems to be ok, but the result of test 3 is kind of weird. Our callback returns undefined when is checking a character that is not a letter, and we’re forming a group with a key named “undefined”.</p><p>We could try to fix this by throwing an error in our callback or by refactoring our groupBy function to prevent pushing values when is not appropiate, but let’s leave it as is so we can compare this with the results of the new <em>Object.groupBy()</em> static method.</p><p>Apart from this, our refactored function seems to be working great! it even works when we pass a string instead of an array as we can see in test 5. This is to be expected since strings are iterables.</p><h3><strong>Object.groupBy</strong></h3><p>Alright. Now we have our tailor made groupBy, which seems to work just fine when we can assure that we’re passing an iterable and kind of ok when passing callbacks. This because we saw in the previous exercise that if we pass a callback that cannot group an item, we end up with a result that is not what we expected (a group with “undefined” as its name).</p><p>Let’s see how we can implement the same two exercises using now the static method <em>Object.groupBy()</em>.</p><p><strong>Note</strong>: this feature is new, and is expected to be published by TC39 in 2024. So check if your environment supports it. <strong>These exercises were executed in Node v21.6.1.</strong></p><h4><strong>Numbers</strong></h4><pre>// Odd and even numbers<br>console.log(Object.groupBy(naturals, evenOrOdd));<br>console.log(Object.groupBy(odds, evenOrOdd));<br>console.log(Object.groupBy(evens, evenOrOdd));<br>console.log(Object.groupBy(empty, evenOrOdd));</pre><p>Result:</p><pre>[Object: null prototype] { odd: [ 1, 3, 5 ], even: [ 2, 4 ] }<br>[Object: null prototype] { odd: [ 1, 3, 5, 7 ] }<br>[Object: null prototype] { even: [ 2, 4, 6, 8 ] }<br>[Object: null prototype] {}</pre><p>Wow!, here we can take some notes about this standard implementation of the method:</p><p>1. The returned object that contain the groups is an object that is not connected through a prototypal chain to any other prototype. Our basic implementation doesn’t comply with this.</p><p>2. We were correct when we assumed that if a potential group doesn’t have items, that group is not present in the result of the method.</p><p>3. We were also correct when we assumed that if no group could be formed, the result is an empty object.</p><h4><strong>Letters</strong></h4><pre>console.table([<br>  Object.groupBy(hello, vowelOrConsonant),<br>  Object.groupBy(vowels, vowelOrConsonant),<br>  Object.groupBy(consonants, vowelOrConsonant),<br>  Object.groupBy(numbers, vowelOrConsonant),<br>  Object.groupBy(greet, vowelOrConsonant),<br>]);</pre><p>Result:</p><pre>┌─────────┬─────────────────────────────────────┬────────────────────────────────────┬─────────────┐<br>│ (index) │ consonants                          │ vowels                             │ undefined   │<br>├─────────┼─────────────────────────────────────┼────────────────────────────────────┼─────────────┤<br>│ 0       │ [ &#39;h&#39;, &#39;l&#39;, &#39;l&#39; ]                   │ [ &#39;e&#39;, &#39;o&#39; ]                       │             │<br>│ 1       │                                     │ [ &#39;a&#39;, &#39;a&#39;, &#39;e&#39;, ... 1 more item ] │             │<br>│ 2       │ [ &#39;w&#39;, &#39;r&#39;, &#39;l&#39;, ... 2 more items ] │                                    │             │<br>│ 3       │                                     │                                    │ [ 1, 2, 3 ] │<br>│ 4       │ [ &#39;h&#39;, &#39;l&#39;, &#39;l&#39;, ... 4 more items ] │ [ &#39;e&#39;, &#39;o&#39;, &#39;o&#39; ]                  │             │<br>└─────────┴─────────────────────────────────────┴────────────────────────────────────┴─────────────┘</pre><p>Nice. This execution can also serve us to learn more about the method:</p><p>1. The method doesn’t check if the value was already inside the assigned group to decide if it should add it or not. The method does push the value regardless of the content of the group. This was a good assumption from our part too.</p><p>2. I thought we would have to refactor our code because of that undefined group! This run indicates that the standard method also forms an undefined group with the values that could not be grouped inside the callback.</p><h3><strong>Final remarks</strong></h3><p>1. We could create a function that makes grouping with the help of a callback function. This basic implementation can help us understand what the new Object.groupBy method does.</p><p>2. This is just a model of what the method is. Nonetheless, always try to use the standard version of the method. You can find the proposal for this addition to Javascript in [here](https://github.com/tc39/proposal-array-grouping). Also check MDN to [see more](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/groupBy).</p><p>3. Check if your environment supports the method before trying to execute the code. The resource in MDN can help you check.</p><p>4. We explored just one part of the proposal. There is also the <em>Map.groupBy()</em> static method. I invite you to see how it works and think about which of the assumptions made about the results of the method groupBy() should be reconsidered.</p><p>5. I talked many times about iterables. You can check more about that concept <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Errors/is_not_iterable">here</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0c2fd5101719" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Learn binary numbers with third-grade math class]]></title>
            <link>https://medium.com/@wfercanas/learning-binary-numbers-by-remembering-third-grade-math-class-cb3ce0b5f21a?source=rss-f521f4b6977e------2</link>
            <guid isPermaLink="false">https://medium.com/p/cb3ce0b5f21a</guid>
            <category><![CDATA[engineering]]></category>
            <category><![CDATA[computer-science]]></category>
            <category><![CDATA[binary]]></category>
            <category><![CDATA[mathematics]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[Fernando Cañas]]></dc:creator>
            <pubDate>Mon, 24 Jul 2023 21:48:29 GMT</pubDate>
            <atom:updated>2023-08-04T16:26:09.772Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*15vOjt87KB-OwyHk" /><figcaption>Photo by <a href="https://unsplash.com/ja/@benwhitephotography?utm_source=medium&amp;utm_medium=referral">Ben White</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Our brain is so used to think in base 10 that we have a hard problem grasping another representation for quantities.</p><p>Its not really an issue for our brains to imagine a basket with 22 apples, but it is <strong>really</strong> a problem if I tell you to go to the grocery store and buy 10110 onions.</p><p>Well, while trying to make my head process this problem and imagine myself buying that amount of onions, I remembered how did my third-grade Math teacher helped me understand that 22.</p><p>Let me share with you how this memory helps me think of base 10 and base 2 numbers.</p><h3>The beans and the box</h3><h4>Base 10</h4><p>Let’s imagine we have a bunch of beans, and our job is to count them. This is what it looks like if we place them in the right-most column of a containerized box:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/444/1*iChgMxo16m5ECRd0B4XIKA.png" /></figure><p>What to do now? They are too many!</p><p>Well, we can form groups. Groups of how many items?</p><ol><li>As many as you want as long as you group them consistently.</li><li><strong>Let’s explore first the path of making groups of ten (Base = 10).</strong></li><li>This decision has a key implication, and is that in each column of the box we can have maximum 9 beans (Base — 1). We’ll explain why and see how it looks when the base is different.</li></ol><p>This is what it looks like:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/444/1*_84US7kwNpdXDZdTZD8l2w.png" /></figure><p>With the groups formed, we can flip the coin. Instead of having 10 units per group, you can think of having 1 group of 10 units.</p><p>With this new point of view in mind, you can replace 10 beans from the first column for one in the second column (from right-to-left).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/444/1*IJhMy-vO9ljL4pktZgvTYA.png" /></figure><p>This means that 1 blue bean in the second column is equivalent to 10 items in the first one.</p><p>As you can see, we left 2 beans in the first column. This is because we can only form groups of 10 to be consistent with our decision. So:</p><ol><li>The number of beans left in a column can vary from 0 to 9.</li><li>If the number of beans were 10, we could had form a new group and leave the column without beans. That’s why the maximum value is 9.</li></ol><p>So, how many beans do we have? Its as easy as joining the amount of beans per column. In this case: 22.</p><p>What happens if the amount of beans were way larger? Let’s see:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/444/1*gNrHLg29TDOA-8hQLKG35w.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/444/1*TwhARdjdY8PaS6vGZ0uBSg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/444/1*n3vBfUXvJSWoe5tPKKDsEA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/444/1*2dWkMBmNlUh4kEta5v3I2w.png" /></figure><p>So, by making new groups of 10 in the second column we can make new replacements and finally conclude that we have 407 beans.</p><p>Take into consideration:</p><ol><li>In the first column we made groups of 10 beans, that’s why in the second column each blue bean represents 10 red beans.</li><li>In the second column we had to make groups too since we had more than 9 blue beans. Each group of 10 means here means that we are grouping 10 blue groups of 10 red beans each.</li><li>After grouping we can perform the replacement. Each group of 10 blue beans is then represented with one purple bean.</li><li>The header of the third column indicates that each purple bean inside is equivalent to 100 red beans.</li></ol><p>I’m sure you get the picture, we can replicate this as many times as we want whenever we need to count whatever items we have at hand.</p><h4>Base 2</h4><p>We initially decided to make groups of 10 items. We did it just because we wanted, but we didn’t have to. We could’ve chosen any number.</p><p>In the base 10 system, a physical amount of beans was equal to this symbol: 22. That symbol has sense in this system, but not in others.</p><p>Let’s see how the same physical quantity of beans can be represented in another base. In this case: base 2.</p><p>You know the rules: consistently make groups of 2 and each column can have maximum 1 bean (base — 1).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/444/1*e-I8sVsLmjyBa58GQB-i9Q.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/444/1*fC1HJRQXS3-0M-5kUiX2Hw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/444/1*7d6ppNAdbP7T8yPg5eT7qA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/444/1*kd-HhFzcaL3F1xCA65FJWg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/444/1*2qiYTqS6cwlJCVuM9X3yJg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/444/1*or9kS_a2S0NQFesP45qIyQ.png" /></figure><p>That’s it! The same physical amount of beans in base 2 is equivalent to 10110.</p><p>We’re sure of it because we started off with the same quantity in both exercises. But we can check using the indexes we added in the previous exercise on top of each column.</p><p>We used those indexes in base 10, and each reflected the total amount of read beans that one bean in each column represents. For example:</p><ol><li>In the base 10 exercise, one bean in the second column represents 10 red beans and one in the third column represents 100 (10*10). In a fourth column we would have 10*10*10 = 1000.</li><li>In base 2, a bean in the second column represents 2 red beans and one in the third represents 4 red beans (2*2). In a fourth column we would have 2*2*2 = 8.</li></ol><p>Continuing with this logic, let’s add those indexes in base 10 to facilitate the conversion and check the exercise.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/444/1*pRrI009uXyDMph5sqVBsfA.png" /></figure><p>If we use the base 10 indexes, you can see that we have: <strong>16</strong>(1) + <strong>8</strong>(0)+ <strong>4</strong>(1) + <strong>2</strong>(1) + <strong>1</strong>(0) = 22. The same!</p><h3>Conclusion</h3><p>When counting physical elements, we may end up with a huge amount of elements. In order to make counting easy, we can break that big problem in smaller problems by making groups of elements.</p><p>The amount of elements we decide to use per group is up to us. We just have to stick to it. Particularly when we complete the first set of groups and we must continue our counting exercise by making groups of groups.</p><p>When there is no more room for grouping, we have finished our algorithm and we can write a representation of how many items we have.</p><p>For the same amount of red beans, we have two representations: 22 and 10110. But that is not the only representation possible, we could’ve made groups of 3, 4, 5, etc.</p><p>If we change the quantities per group, we will get a different representation.</p><p>Yes, we are sooo used to work in base 10, that it is way too easy for our brains to work with the representations that the system gives us. We can imagine those quantities. But be wary, it is not the only way we can treat quantities.</p><p>When you enter the world of computing, you will need to become familiar with the base 2 universe.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cb3ce0b5f21a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Load fonts on demand with React]]></title>
            <link>https://medium.com/@wfercanas/load-fonts-on-demand-with-react-206ce12174c0?source=rss-f521f4b6977e------2</link>
            <guid isPermaLink="false">https://medium.com/p/206ce12174c0</guid>
            <category><![CDATA[design-systems]]></category>
            <category><![CDATA[token]]></category>
            <category><![CDATA[typography]]></category>
            <category><![CDATA[front-end-development]]></category>
            <category><![CDATA[react]]></category>
            <dc:creator><![CDATA[Fernando Cañas]]></dc:creator>
            <pubDate>Fri, 30 Jun 2023 17:23:03 GMT</pubDate>
            <atom:updated>2024-01-22T22:02:58.897Z</atom:updated>
            <content:encoded><![CDATA[<h3>Load fonts with FontFace API and React</h3><p>I’m building a portal that can be used by multiple clients. One GitHub repo, multiple instances — one per client — .</p><p>Each client wants to customize part of the UI so it reflects their own aesthetics, and a key element here is the usage of fonts.</p><p>In this article, I will explain how I’m solving the issue using typography tokens, theme provider, google fonts and custom hooks.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*H1XTSiA6xHhOWBB4" /><figcaption>Photo by <a href="https://unsplash.com/@brett_jordan?utm_source=medium&amp;utm_medium=referral">Brett Jordan</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>Typography Tokens</h3><p>For tokens, I’m using a BEM structure. Here I show you how does it work in more detail using colors (<a href="https://medium.com/@wfercanas/using-bem-for-design-system-tokens-bem-tokens-46795339a893">see article</a>).</p><p>Briefly, a BEM token consists of 5 parts: entity, domain, block, element and modifier:</p><ul><li><strong>Entity</strong>: is the client (e.g. acme)</li><li><strong>Domain</strong>: are the foundations of the design system, here I will talk about typography, but that could be color, spacing, etc.</li><li><strong>Block</strong>: are meaningful parts of the domain. In colors we can have colors for texts, strokes or surfaces. In typography we have headlines, labels, paragraphs, titles, etc.</li><li><strong>Element</strong>: are meaningless parts if they are not attached to a block. In terms of colors we have reds, blues, yellows and so on. In typography we have sizes: small, medium, large.</li><li><strong>Modifier</strong>: are subtle modifications we make to elements. In colors we have tones of color, in typography we have lineHeight, weight, tracking — letter-spacing — , etc.</li></ul><p>So, we could have these tokens for acme:</p><ul><li>acme.typography.label.large.size = 16px</li><li>acme.typography.label.large.lineHeight = 18px</li><li>acme.typography.label.large.weight = 500</li><li><strong>acme.typography.label.large.font = “Open Sans, sans-serif”</strong></li></ul><p>In practice, if we need to add a label in its large variant inside a card and we have a &lt;Text /&gt; component to make it work, it would look like this:</p><pre>function Card() {<br>  return (<br>    &lt;div&gt;<br>      &lt;Text as=&quot;label&quot; type=&quot;label&quot; size=&quot;large&quot;&gt;acme&lt;/Text&gt;<br>    &lt;/div&gt;<br>  )<br>}<br><br>function Text({children, as = &#39;p&#39;, type, size}) {<br>  return (<br>    &lt;StyledText as={as} type={type} size={size}&gt;<br>      {children}<br>    &lt;/StyledText&gt;<br>  )<br>}<br><br>const StyledText = styled.p`<br>  font-size: ${({type, size}) =&gt; acme.typography[type][size].size};<br>  font-weight: ${({type, size}) =&gt; acme.typography[type][size].weight};<br>  letter-spacing: ${({type, size}) =&gt; acme.typography[type][size].tracking};<br>  line-height: ${({type, size}) =&gt; acme.typography[type][size].lineHeight};<br>  font-family: ${({type, size}) =&gt; acme.typography[type][size].font};<br>`</pre><p>Here I’m using <a href="https://styled-components.com/">styled-components</a> and props to determine how to style the component, but the styles are extracted from the token system with the BEM structure we just saw.</p><p>Given the fact that we don’t want to hardcode the client into the styles definition, we must make use of a theme provider, which in React tends to be an implementation of the useContext hook under the hood.</p><h3>Theme Provider</h3><p>Continuing with the use of styled-components, we have inside the library the <a href="https://styled-components.com/docs/advanced#theming">&lt;ThemeProvider /&gt;</a> component.</p><p>With this component, we can define a theme, pass it as props to the provider and guarantee that each styled-component we create will have access to that theme.</p><p>It’s like this:</p><pre>import { ThemeProvider } from &#39;styled-components&#39;<br><br>const theme = {<br>  /* client tokens */<br>};<br><br>function App() {<br>  return(<br>    &lt;ThemeProvider theme={theme}&gt;<br>      &lt;Text as=&quot;label&quot; type=&quot;label&quot; size=&quot;large&quot;&gt;acme&lt;/Text&gt;<br>    &lt;/ThemeProvider&gt;<br>  )<br>};<br><br>function Text({children, as = &#39;p&#39;, type, size}) {<br>  return (<br>    &lt;StyledText as={as} type={type} size={size}&gt;<br>      {children}<br>    &lt;/StyledText&gt;<br>  )<br>};<br><br>const StyledText = styled.p`<br>  font-size: ${({theme, type, size}) =&gt; theme.typography[type][size].size};<br>  font-weight: ${({theme, type, size}) =&gt; theme.typography[type][size].weight};<br>  letter-spacing: ${({theme, type, size}) =&gt; theme.typography[type][size].tracking};<br>  line-height: ${({theme, type, size}) =&gt; theme.typography[type][size].lineHeight};<br>  font-family: ${({theme, type, size}) =&gt; theme.typography[type][size].font};<br>`</pre><p>Since we are using useContext under the hood, we don’t have to pass the theme through props. The StyledText component have access to it on its own.</p><p>I may set the theme with the acme tokens or any other client. It would be just a matter of fetching from an endpoint the tokens for the desired client and set the theme with that information.</p><p>Everything looks easy up until now, but we have to solve the font-family CSS rule, because we may have a client whose font isn’t by default in the browser, so we have to somehow download it.</p><p>Let’s see how.</p><h3>Google Fonts</h3><p>If we access <a href="https://fonts.google.com/">fonts.google.com</a>, we have access to a wide variety of fonts that we can use in our projects. The most common way to use these resources is to copy the &lt;link&gt; elements for the set of fonts we want to use and paste them inside the &lt;head&gt; element of our html document.</p><p>Through this &lt;link&gt; element, which at the end is of rel=”stylesheet”, we are defining a set of CSS rules related to font faces (@font-face). If you want, you can click on this example and your browser will show you these rules: <a href="https://fonts.googleapis.com/css2?family=Open+Sans&amp;display=swap">https://fonts.googleapis.com/css2?family=Open+Sans&amp;display=swap</a></p><p>If you look carefully, there is a rule for the different ranges of unicode characters. For simplification, we can use just the rules for latin ranges.</p><p>So, how do we use this? I had to create a new backend endpoint apart from the one that I use to get each client tokens. This new endpoint gives me information about a specific font I’m needing. The JSON I get looks like this:</p><pre>{<br>  &quot;Open Sans&quot;: [<br>    {<br>      &quot;family&quot;: &quot;Open Sans&quot;,<br>      &quot;url&quot;: &quot;https://fonts.gstatic.com/s/opensans/v35/memvYaGs126MiZpBA-UvWbX2vVnXBbObj2OVTS-muw.woff2&quot;,<br>      &quot;options&quot;: {<br>        &quot;weight&quot;: 400,<br>        &quot;style&quot;: &quot;normal&quot;<br>      }<br>    },<br>    {<br>      &quot;family&quot;: &quot;Open Sans&quot;,<br>      &quot;url&quot;: &quot;https://fonts.gstatic.com/s/opensans/v35/memvYaGs126MiZpBA-UvWbX2vVnXBbObj2OVTS-muw.woff2&quot;,<br>      &quot;options&quot;: {<br>        &quot;weight&quot;: 500,<br>        &quot;style&quot;: &quot;normal&quot;<br>    }<br>  ]<br>}</pre><p>The url for each variation can be extracted from the CSS rules you see when you open the link that google fonts gives you.</p><p>To get all the fonts you may need, you should:</p><ol><li>Fetch the tokens of the client</li><li>Look inside the typography tokens and find all the different fonts defined there — for acme its just “Open Sans” but another client may want “Roboto” for titles and “Lato” for paragraphs, for example — .</li><li>Once you have the list of fonts, you can fetch this last JSON from the service that gives you information about the fonts.</li></ol><p>Now your project knows where to get the fonts. Now its time to download them and make them work in your project.</p><h3>useFonts</h3><p>Let’s split this part in two:</p><h4>FontFace API</h4><p>Thankfully, there is a Web API that will save the day for us. The FontFace API allow us to define a new font-face object using JavaScript — works just like the @font-face rule for CSS, but with some helpful methods — .</p><p>For creating a new FontFace object, we must know the family, the URL where the font can be downloaded from and some font configuration options like weight or style.</p><p>You can see here more information about the <a href="https://developer.mozilla.org/en-US/docs/Web/API/FontFace">FontFace API</a> and compare it with the <a href="https://internetingishard.netlify.app/html-and-css/web-typography/index.html">traditional way of using font-faces with CSS</a>.</p><p>Following the structure of the JSON we got from the service, we can define one FontFace object for each variant like this:</p><pre>const fontFaces = fonts.map((font) =&gt; {<br>  return new FontFace(font.family, `url(https://medium.com/$%7Bfont.url%7D)`, font.options)<br>})</pre><p>With the objects created, we can now define a function to load a fontFace and then add that font to the document:</p><pre>async function loadFontFace(fontFace) {<br>  const loadedFont = await fontFace.load();<br>  document.fonts.add(loadedFont);<br>}</pre><p>This function is asynchronous because the load methods returns a promise that is resolved when the fontFace gets loaded.</p><p>With these two elements, we can now create our custom hook.</p><h4>useFonts() hook</h4><p>Good, lets make this hook receive as an argument the fonts to load, so, using what we have up until now the hook would look like this:</p><pre>import { useState, useEffect } from &quot;react&quot;;<br><br>function useFonts(fonts) {<br>  const [fontFaces] = useState(<br>    fonts.map((font) =&gt; {<br>      return new FontFace(font.family, `url(https://medium.com/$%7Bfont.url%7D)`, font.options);<br>    })<br>  );<br><br>  async function loadFontFace(fontFace) {<br>    const loadedFont = await fontFace.load();<br>    document.fonts.add(loadedFont);<br>  }<br><br>  useEffect(() =&gt; {<br>    fontFaces.forEach((fontFace) =&gt; {<br>      loadFontFace(fontFace);<br>    });<br>  }, [fontFaces]);<br>}<br><br>export { useFonts };</pre><p>The point here is that we can re-render the interface if there is a change related to the fontFaces state.</p><p>Then you can just use the hook in the root part of the project:</p><pre>import { Text } from &quot;./components/Text&quot;;<br>import { ThemeProvider } from &quot;styled-components&quot;;<br>import { useFonts } from &quot;./hooks/useFonts&quot;;<br><br>function App() {<br>  const theme = {};<br>  const fonts = [];<br>  /* fetch theme and set it */<br>  /* fetch fonts information */<br><br>  useFonts(fonts);<br><br>  return (<br>    &lt;ThemeProvider theme={theme}&gt;<br>        &lt;Text as=&quot;label&quot; type=&quot;label&quot; size=&quot;large&quot;&gt;<br>          Hello World<br>        &lt;/Text&gt;<br>    &lt;/ThemeProvider&gt;<br>  );<br>}<br><br>export default App;</pre><p>Since the loading of fonts can take some times — usually ms — I recommend you to also have a default and similar font that is already in the browser. This prevents that the user gets to see an abrupt change in the screen once the fonts are loaded.</p><p>This default font can be defined per client using the corresponding token. For example: acme.typography.label.large.font = “Open Sans, Arial, sans-serif”.</p><p>With this system, I extended the use of BEM tokens to work with typography and also allowed the project to dynamically load fonts depending on the client that is using the product.</p><p>Hope this experience is useful for you.</p><p>Thanks for reading!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=206ce12174c0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Using BEM for design-system tokens (bem-tokens).]]></title>
            <link>https://medium.com/@wfercanas/using-bem-for-design-system-tokens-bem-tokens-46795339a893?source=rss-f521f4b6977e------2</link>
            <guid isPermaLink="false">https://medium.com/p/46795339a893</guid>
            <category><![CDATA[colors]]></category>
            <category><![CDATA[token]]></category>
            <category><![CDATA[design-systems]]></category>
            <category><![CDATA[design]]></category>
            <category><![CDATA[front-end-development]]></category>
            <dc:creator><![CDATA[Fernando Cañas]]></dc:creator>
            <pubDate>Fri, 23 Jun 2023 21:27:52 GMT</pubDate>
            <atom:updated>2023-06-23T21:27:52.796Z</atom:updated>
            <content:encoded><![CDATA[<p>I’ve been working on building from scratch a design-system and tokenization has been quite hard to grasp. After trying some structures — i.e. <a href="https://m3.material.io/styles/color/the-color-system/tokens">Material Design</a> or <a href="https://atlassian.design/tokens">Atlassian Design System</a> — , I decided to take some ideas from them and define a new token structure that can be easier to follow.</p><p>Let me show you using <strong>colors</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*42135Ab7rZyYGmBM" /><figcaption>Photo by <a href="https://unsplash.com/@stationery_hoe?utm_source=medium&amp;utm_medium=referral">Kasturi Roy</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>Token structure</h3><p>Let’s start by explaining the structure of the tokens. The tokens are built using the following building blocks:</p><ul><li>Domain</li><li>Block</li><li>Element</li><li>Modifier</li></ul><p>So, A token is the connection between them in the form: <strong>domain.block.element.modifier</strong>.</p><p>Examples of this could be <strong>color.surface.warning.regular </strong>or <strong>typography.body.large.regular.</strong></p><h4>Domain</h4><p>The domain part of the token allows you to access the pilars of the design-system, its foundations. There you can find domains such as color, typography or spacing.</p><h4>BEM</h4><p>The other parts of the tokens are related with a BEM structure (Block-Element-Modifier). This is originally an approach to work with CSS classes. With BEM we have a consistent way of styling our components, particularly in projects that start growing in size. <a href="https://getbem.com/introduction/">See more</a>.</p><p>A <strong>block</strong> should be meaningful on its own. Applied to CSS classes it could be a header or a nav.</p><p>An <strong>element</strong> should be tied to its block, because it is meaningless on its own. Continuing with the previous examples, the element could be a logo or a link but tied to their blocks like header logo or nav link .</p><p>Finally, we have the <strong>modifier</strong>. Their role is to change an element, so that it can be displayed in different ways depending on its context. You can think of them like CSS pseudo-classes. So, in the example of the nav link , we can have it in its regular, hovered or selected states: nav link regular, nav link hover ornav link select.</p><h3>Color Tokens</h3><h4>Palette</h4><p>Focusing on the color domain, the first <strong>block</strong> to define is the Palette block. Here we will create the universe of colors to use in the design-system.</p><p>For this domain, the <strong>elements</strong> are the group of colors we want to use. Particularly, we created these groups following the <a href="https://atlassian.design/foundations/color-new/color-palette-new/">Atlassian structure for colors</a>: yellow, green, blue, teal, purple, red, neutral (which is just a grayscale).</p><p>For each element, that is, a color group, we define different combinations of colors related to that group — <strong>modifiers — </strong>. Here we also opted to use the color system proposed by Atlassian coding each color with an alphanumeric reference. The result for the blue element looks like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2dshA6rHSgN_WNmFwq_GIg.png" /><figcaption>Token parts and values for a blue element</figcaption></figure><p>So, in terms of tokens, the <strong>color.palette.blue.b500</strong> token equals the HEX color #0747A6.</p><p>You can do the same for the rest of elements (yellow, red, green, etc.).</p><p>In the case of the neutral element, I also sticked to the graduation Atlassian makes. I created way more modifiers, ranging from N900 to N100 in decrements of 100, and from N90 to N0 in decrements of 10.</p><h4>Texts</h4><p>Now that the palette is defined, it is possible to continue with other interesting blocks for the <strong>color</strong> domain. Let’s see the <strong>text</strong> block.</p><p>The tokens defined here apply to any text inside the products developed using this design-system. Let’s see:</p><ul><li>Domain: color.</li><li>Block: text.</li><li>Elements: primary, success, error, warning, information, help, link, and so on.</li><li>Modifiers: regular, hover, disabled, crossed, and so on.</li></ul><p>With this structure, the tokens for primary and success texts could look like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Jn397JNqD2Nx_ageXIb2BQ.png" /></figure><h4>New blocks and elements</h4><p>This structure can be repeated for other blocks as well. You can use it for <strong>color</strong>.<strong>strokes</strong> and <strong>color.surfaces</strong>, for instance.</p><p>For each block, you can define the same set of elements — primary, success, error, warning — , or include some new ones — I eventually added the dark, gray and light elements to all blocks (including text) — .</p><h4>Entities</h4><p>The design system I’m creating should be customized by our clients. This means that although we develop a unique app which implements the design-system, this app should be deployed for each of our clients, and each one those deploys should have the look and feel of the respective client aesthetics.</p><p>This is a key requirement since the app will end up being used by the customers of our clients, and these customers should log in and feel like they are in our client’s app.</p><p>So, for this case, we added a new building block to the token structure, using the client name as an entity that prefixes the tokens. So, the universe of colors for ACME can be referenced by using <strong>acme.color.palette</strong>…., and the universe of colors for LEXCORP through <strong>lexcorp.color.palette</strong>….</p><p>If you find yourself in this situation or if the aesthetics depends on some other variable, you can replace the entity attribute for another one. For instance, if you develop multiple apps and each one of them should have their own theme, you can append the theme attribute or even the app name.</p><h3>Components</h3><p>In order to illustrate how do the tokens impact a component, lets see two &lt;Flag /&gt; components where the color tokens are used:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/780/1*WnwwodlToU0q_l_3WrddCQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/780/1*V8QzzXtge9eJ5i9_tkVIqA.png" /></figure><h3>Conclusion</h3><p>I will be using this structure for building a design-system that works for multiple clients.</p><p>In the case of colors, each client will be able to define their own palette and with the palette, add semantics to texts, strokes, surfaces and more so that their deployed app looks like their own.</p><p>For colors and other domains, the idea is to keep the BEM structure. Perhaps typography, spacing, border, or elevation domains present new challenges in terms of how to make them work within this structure, but I think it is possible to find a way.</p><p>Reusing this template for tokens, in my opinion, is way easier to work with than some other options you may find around.</p><p>I’ll be posting about how do this work goes and also some analysis about why the other options didn’t work for me.</p><p>See ya!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=46795339a893" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Be a startup again when trying to innovate with a new product]]></title>
            <link>https://medium.com/design-bootcamp/be-a-startup-again-when-trying-to-innovate-with-a-new-product-c2c4a2a5cf00?source=rss-f521f4b6977e------2</link>
            <guid isPermaLink="false">https://medium.com/p/c2c4a2a5cf00</guid>
            <category><![CDATA[product-management]]></category>
            <category><![CDATA[innovation]]></category>
            <category><![CDATA[product]]></category>
            <category><![CDATA[startup]]></category>
            <category><![CDATA[design]]></category>
            <dc:creator><![CDATA[Fernando Cañas]]></dc:creator>
            <pubDate>Thu, 09 Jun 2022 15:17:54 GMT</pubDate>
            <atom:updated>2022-06-11T16:29:23.823Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="A team gathered together working on planning their tasks" src="https://cdn-images-1.medium.com/max/1024/1*VRqhiGXK_mm2vINmznL_sQ.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/es/@jasongoodman_youxventures?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Jason Goodman</a> on <a href="https://unsplash.com/s/photos/digital-product?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>Every successful company has passed through the following stages: startup, growth and consolidation.</p><p>Let’s see what these stages are about. Then, I will show you three reasons why it is important to walk again the same road whenever an established company wants to innovate with new products.</p><h4>Startup</h4><p>In this stage the objective is basically one: find a favorable market position — market-fit — . This means, define the product that the market is willing to buy and that the company is in conditions to produce profitably.</p><p>It is necessary to experiment, learn and pivot fast so the product may find its right path.</p><h4>Growth</h4><p>If the product has find its market-fit, the pains of growing appear. To increase the scale of what the company has been doing up to this point is a tough task. There are many internal dynamics that have been popping-up from the immediate necessities and not all of them can scale to a greater productive level in a satisfactory way.</p><p>Moreover, to grow also implies that you must start considering aspects of the business that were not a priority in the startup stage. Now, these new elements should grow and get integrated with the hectic pace of a business that barely survives while it grows.</p><h4>Consolidation</h4><p>Here the product reaches a meaningful level of maturity and the internal dynamics of the business start settling. Job specialization is more evident now. It is easy to identify who is in charge of each operation and where are the limits of each team.</p><p>The job specialization in some places allow you to achieve deep knowledge in many complexities of the business. This is possible because the business can afford to invest time and resources in areas that are important but not urgent.</p><p>This road teaches so much, but also demands grit to be completed. Lets see then three justifications that consolidated companies make to avoid walking the whole road again when they are trying to innovate with new products. Lets check also why that route may not be the best.</p><h3>Three justifications to skip steps of the road and their potential costs</h3><h4>It is not necessary to validate the market again</h4><blockquote><em>“We already have enough experience in this sector, so we can make a good guess about what works and what doesn’t. It is not necessary to invest money to test idea after idea until we find a market-fit.”</em></blockquote><p><strong>Costs:</strong> What we see here is that the company is deciding to jump the startup stage altogether. According with this stance, it is not necessary to connect with customers nor present ideas to test them. Possible costs of this may be:</p><ol><li>The product finally doesn’t get sales and you learn the lesson after a lot of working hours invested. You learn late and costly.</li><li>The idea is not an idea built by the team, the idea is an instruction. The company skips the part where they have to defend the idea in front of a user or a potential investor as if the company’s survival depends on it. People’s hearts are not involved so you have at the end a heartless product that no one wants to buy.</li><li>To advance with the project without starting to sell as soon as possible is only possible because of the financial support an established company provides to the project. This comfort generates that this iniciative didn’t have to fight hard to sell the product. Those resources invested were used to delay facing reality. Again, you learn late and costly.</li></ol><h4>We will do it how we operate our current products</h4><blockquote><em>“Our current processes work, it is just a matter of hiring more people and replicate what we do now. In fact, we can do it with the people we already have, its just a matter of looking for more efficiency.”</em></blockquote><p><strong>Costs</strong>: Here the company is assuming that what worked once will work again, that you only have to check the details. The costs may be:</p><ol><li>The operations become recipes and not the backup the product needs to be successful. You end up using what you have without evaluating and experimenting what is it that the product needs to prosper. The user experience (UX) at the end may be pretty poor and you see and feel that the processes are disconnected from the product in their roots.</li><li>The product evolution speed is drastically lower than the speed of the first product. A consolidated system may be an excessive burden for a newborn product, a system that is unable to adapt fast to the changes that the product demands. This way may lead to the dead of the idea because the lack of fast reaction from the company.</li><li>One thing is to look for efficiencies in a process that has a clear objective, another thing is to look for efficiencies so you can add a new objective that is a rival of the first. This may cause that the idea dies or that the consolidated business gets weakened. At the end, the business that creates the revenue usually wins and the new idea dies.</li></ol><h4>Excess of complexity</h4><blockquote><em>“After creating and supporting our current products, we are capable of understanding in a deeper level what we need to do to create a successful product. We can split the job into different parts and make each team tackle some of them. Like this we join the parts at the end and achieve a great product.”</em></blockquote><p><strong>Costs</strong>: Here the company is trying to use its full capacity and deep knowledge to create a great product, but is the engineering side of the problem the one that determines the product and not the user validated needs. The costs may be:</p><ol><li>A significant number of highly qualified people enter the project and start creating partial deliverables of the product. This investment may result in a product that is highly competent in an engineering perspective but that the user doesn’t want or buy. This is just a huge waste of value.</li><li>Even if the company achieves a product that is desired and generates sales, maybe only 20% of their features add value to the client. A real startup wouldn’t have so many resources, so it would be necessary to align them to produce the features that added the most value. Here you have a lot of product features that are a waste of value.</li><li>When you support a product, such support is for the whole product. The problem here is that the product may have a greater degree of complexity than necessary. You pay the price with the slow pace at which you can create new value, because you have to be more careful to keep the product working with all the complexity involved.</li><li>A simpler user experience could increase customer fidelization. The competence can read what provides value and what doesn’t so they can create a rival product that sells even more and that is faster in terms of adapting it to the market. The company’s new product becomes obsolete soon.</li></ol><p>These are just three justifications that I’ve seen when a consolidated company decides to use when trying to innovate with new products, so they don’t have to walk the whole road of a startup again.</p><p>Yes, it is important to capitalize all the experience you gain over the years, it is not about starting from scratch.</p><p>What it is about is that you should walk the road again, execute the whole process with all your knowledge and capabilities, so you can now create high value products that no one else but you can create. At least not with ease.</p><p><strong>Are there other justifications to skip steps of the process of a startup? Let me know!</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c2c4a2a5cf00" width="1" height="1" alt=""><hr><p><a href="https://medium.com/design-bootcamp/be-a-startup-again-when-trying-to-innovate-with-a-new-product-c2c4a2a5cf00">Be a startup again when trying to innovate with a new product</a> was originally published in <a href="https://medium.com/design-bootcamp">Bootcamp</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Listen And Lead As Basis For Creating Awesome Products]]></title>
            <link>https://medium.com/@wfercanas/listen-and-lead-as-basis-for-creating-awesome-products-1e137873c23d?source=rss-f521f4b6977e------2</link>
            <guid isPermaLink="false">https://medium.com/p/1e137873c23d</guid>
            <category><![CDATA[coffee]]></category>
            <category><![CDATA[product-management]]></category>
            <category><![CDATA[dreams]]></category>
            <category><![CDATA[leadership]]></category>
            <category><![CDATA[product]]></category>
            <dc:creator><![CDATA[Fernando Cañas]]></dc:creator>
            <pubDate>Sun, 05 Jun 2022 18:05:34 GMT</pubDate>
            <atom:updated>2022-06-05T18:05:34.325Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0Q0wFcZz8KwiJ6auv46gGg.jpeg" /><figcaption>Photo by Roman Kraft on Unsplash</figcaption></figure><p>I understand that frequently our minds conceive new product ideas that we believe can be successful. Products that solve problems we think are meaningful, so the only thing that is left to do is to just start creating them.</p><p>The idea may get boosted quickly if you have the chance to gather a team soon to start building. Stop. Let’s think a little more before jumping in.</p><h3>Let’s Check If Someone Desires It</h3><p>Perhaps the problem we got at hand is relevant only for us. Perhaps it is important for many, but they can live perfectly without our solution.</p><p>Before beginning to build anything, <strong>we should drink a lot of coffees</strong>. Coffees with people, coffees with friends, colleagues and unknown persons. People with whom we can talk about the problem and why it matters to solve it.</p><p>It is importat to talk and see how vibrant is the conversation.</p><p>If we don’t get to move the people that live with intensity the problems we aim to solve, maybe is better to leave the idea right there. At the end, although the decision of using our products may be rational, it is in a greater degree an emotional one.</p><h3>Stick It On The Wall</h3><p>When I was a kid I used to dream about becoming a professional soccer player. Many of us did. Almost all of us sticked a poster of our favorite player on the wall.</p><p>When you do this, you are no just sticking a piece of paper or a photo. You are sticking a dream.</p><p>When you wake up you see it, when you play with your friends you make pretend your are him/her. When you see them in TV you admire them, when they score you celebrate, when they fall you cry. You look at their details, their passes, their way of running, jumping and dodging.</p><p>I believe we should do the same with our product ideas. After so many coffees, we should have a flag to raise. A poster to stick on the wall. You are not building anything yet, but you do dedicate time to visualize the product with their compelling details.</p><p>We need a poster to see what we want to become. Let’s build the poster of our product and stick it on the wall. Visualize your dream and achieve it.</p><h3>Lead, Don’t Dictate</h3><p>There is no way in which you can achieve the dream on your own. It doesn’t work that all the decisions that enable a product to grow and be successful flow only from you. It is also useless that you decide to save all the tough decisions for yourself.</p><p>Gathering all the power about what can and cannot be done with the product will only leave you as a lone dreamer. If you share the vision, lead, assist the process, advise and delegate, you will create the room for other people to dream what you dream. Only if your team dreams intensively as you, you will succeed.</p><h3>Gather The Team</h3><p>If you are ready to do this, gather your team and conquer. Remember, even if you start building your dream, <strong>never stop drinking coffees</strong>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1e137873c23d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Human Biases in Software Development]]></title>
            <link>https://medium.com/@wfercanas/human-biases-in-software-development-9a10103b9a9a?source=rss-f521f4b6977e------2</link>
            <guid isPermaLink="false">https://medium.com/p/9a10103b9a9a</guid>
            <category><![CDATA[bias]]></category>
            <category><![CDATA[teamwork]]></category>
            <category><![CDATA[technology]]></category>
            <category><![CDATA[product]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[Fernando Cañas]]></dc:creator>
            <pubDate>Sat, 24 Jul 2021 18:47:12 GMT</pubDate>
            <atom:updated>2021-07-25T03:50:19.960Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*YulSjpHjiNcC9Et4" /><figcaption>Photo by <a href="https://unsplash.com/@soymeraki?utm_source=medium&amp;utm_medium=referral">Javier Allegue Barros</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>This article is a reaction to the “8 Cognitive Biases in Software Development” article written by Matthieu in its webpage <a href="https://thevaluable.dev/cognitive-bias-software-development/">The Valuable Dev</a>. I plan to make a quick brief of the key topics of that article, highlight certain positions and debate some others. Let’s go!</p><h3>Quick Brief</h3><p>Matthieu points out several biases that are inherently present when we as humans are involved in making software (and I think this can be extended to whatever we intend to create, more so if it is a complex task). These biases are:</p><h4>The Optimisic Bias</h4><p>Is the “tendency to be unrealistically optimistic about events happening around us”. In action it means we expect to solve challenges easily and internalize that assumption without checking the facts.</p><p>This tend to be more present when setting expectations about abstract and long term tasks.</p><h4>The Overconfidence Bias</h4><p>Although not entirely developed in the article, we can get from it that is tightly related to the optimistic bias. In fact, that optimistic view in the future can be explained by the fact that we have pretty much confidence in our technical abilities. The overconfidence bias starts when even if we are proficient facing technical challenges, we think we are better than we actually are or our current abilities really don’t match the challenges to come — recall that part where we avoided checking the facts before stating an optimistic posture — .</p><h4><strong>The Confirmation Bias</strong></h4><p>This bias highlights the tendency we have to only pay attention to the information that confirms our beliefs and pretty much ignore the ones which challenges them. Guess there is no need to add much, we love being right! And we give too much relevance to the facts that support our points of view and too little to the ones that don’t.</p><h4>Wishful Thinking</h4><p>This one isn’t discussed much in the article, but I get that it is more a human trait that makes us hope for the best of the outcomes (optimistic again) with the best of all possible worlds happening while achieving such outcome. Guess optimistic bias is related to the soon and smooth realization of the outcome while wishful thinking adds to the situation the overlooking of risks in the process (!Murphy’s Law).</p><h4>The Anchoring Bias</h4><p>The bias appears when our opinions are only based in the initial information we get, no matter if everything else proves us wrong. Particularly means that the capacity to question ourselves and what we “know” is not as powerful as we think it is. This makes us perpetuate behaviors, patterns and decisions even when all around us is evidence that we’re doing it all wrong.</p><h4>The Bandwagon Effect</h4><p>We always will struggle when going against the current. When everybody is walking in a certain direction and we are not so sure about where to go, we will probably end up walking with them. To go against the current demands to think deep about the problem at hand, something that may not always be the case if we involve all the previous biases. Also, you assume that if they are walking in that direction is because they know better — more so if you don’t have a clue of where to go — , so you join them. Name they “senior” people, and you surely get the point.</p><h4>The Cargo Cult</h4><p>Not so much to comment here. This one pushes us to follow blindly what the others do. Matthieu combines this one with the bandwagon effect so if you like, you can find more on this specific point <a href="https://en.wikipedia.org/wiki/Cargo_cult">here.</a></p><h4>The Correspondence Bias</h4><p>This one is tough for humans as teamplayers. This pushes us to explain behaviors and results mainly based in personality traits or individual technical competence — or lack of it — without rightly involving the environment and specific situation that produced them. Is more clear when we are checking the work of someone else and we jump to conclusions linking the outcome to that person personality and competence, while when we or someone else checks our own work then we do decide to include all sorts of environmental and contextual information to judge the outcome.</p><p>Here I briefed the biases exposed in the article, but I didn’t mention the tactics it offered to deal with them. I recommend you to check them, because there are practical insights that can help you a lot in the future when creating software solutions or any other complex product, specially when doing it within a team.</p><p>Now, let me explain my position about the article through three ideas that I think can be valuable in this conversation.</p><h3>I Would Change the Article’s Name</h3><p>If we analyze all those biases, they are all based in our human nature. That human nature is profoundly complex so we shouldn’t reduce the scope of the conversation solely to our cognitive dimension. That’s why I called this post “Human Biases in Software Development”, because to explore this field and to create solutions that makes us work better together and produce valuable results, we need to see ourselves as we are. My feeling while reading the article was that the article’s name is biased 😅.</p><h3>Let’s Stop Complaining About Meetings!</h3><p>Please, please, let me say it again: let’s stop complaining about meetings! I know that jokingly Matthieu uses several example situations about meetings to place you in a known situation to clarify a point, but more jokingly is the fact that by checking the solutions he offers to keep in control our biases, most of them demand that we as humans collaborate to create new perspectives, to device processes that help us reflect on our assumptions and to commonly test them.</p><p>Phrases like “<em>Bad News, you’re in the meeting room</em>” or “<em>You are in a feature meeting. Again. Don’t worry, it will be over soon.</em>” I think don’t help. Yes, we must make big efforts to face our biases to create value, but we also must make big efforts to have valuable meetings, the ones that will enable teams to think deep, to not oversimplify things, to check facts, to manage risks, to empower each team member to speak up when everybody is walking in a direction he or she is not so sure its right or worth it.</p><p>Jokes are good to connect with the readers, more so in common situations that help you position your readers in a context that enlights the argument. Nonetheless, in this case I think the joke harms a key point in the discussion, which is that the nature of the problem is human-based and that its solutions are also human-based, we need to cooperate to keep in check our biases, join our perspectives and create better outcomes.</p><h3>Scientific Thinking and Speed</h3><p>I fully agree with the debiasing methods offered by Matthieu to manage this human biases, even more when dealing with complex situations. So, in the line of thinking different and proposing new perspectives, I would like to add an embrace biases method splitted in two parts:</p><h4>There should be fun in facing them!</h4><p>Solving problems that includes all these sort of challenges should be fun! More so if we are dealing with them as a team. There is only one cosmos — at least known by us — but there is a world for each living human. World in this context means all that each of us know and have experienced.</p><p>If we must collaborate to create valuable products, we must share our worlds. Enjoy knowing life through the complexities of your own world mixed with your teammates worlds, be willing to create a vision together and be willing to put it to test. Although is good to have methods to keep under control our biases, also enjoy the process of bringing to life a solution that had to face all the biases of all of the humans that made it possible.</p><h4>Set an hypothesis, test and learn fast</h4><p>Just like the process of knowing each other’s world is full of endless stories, so is the process of creating software as teams. The vision you set may be full of biases but it shouldn’t matter as much as it is to put it to test. Create a story together and see if it can become a reality, test it rigorously, learn about it, device new ways of seeing your points of view in new perspectives and iterate again. Do it fast. Do so and you will create awesome products and enjoy life with all its complexities as well.</p><h3>Notes</h3><p>Thanks for reading! here I share the notes I took while reading Matthieu’s article if you want to use them:</p><p><a href="https://wfercanas.notion.site/8-Cognitive-Biases-in-Software-Development-a029e3f3ce9244299fe81bf02380f8f7">https://wfercanas.notion.site/8-Cognitive-Biases-in-Software-Development-a029e3f3ce9244299fe81bf02380f8f7</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9a10103b9a9a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[aclararConceptos (Front-End, Back-End, Client-Side, Server-Side);]]></title>
            <link>https://medium.com/@wfercanas/aclararconceptos-front-end-back-end-client-side-server-side-4c36b82a550d?source=rss-f521f4b6977e------2</link>
            <guid isPermaLink="false">https://medium.com/p/4c36b82a550d</guid>
            <dc:creator><![CDATA[Fernando Cañas]]></dc:creator>
            <pubDate>Fri, 14 Aug 2020 22:57:43 GMT</pubDate>
            <atom:updated>2020-08-14T23:30:48.562Z</atom:updated>
            <content:encoded><![CDATA[<h3>aclararConceptos (Front-End, Back-End, Client-Side, Server-Side)</h3><figure><img alt="Laptop on a desk with a browser open" src="https://cdn-images-1.medium.com/max/1024/0*n-rkdU5N-_xFZ1Sd" /><figcaption>Photo by <a href="https://unsplash.com/@kundeleknabiegunie?utm_source=medium&amp;utm_medium=referral">Agnieszka Boeske</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Antes de empezar, doy en gran parte el crédito del contenido de este texto a <a href="https://medium.com/u/507c630f8e43">Timi Ajiboye</a>, quien hizo un artículo genial sobre estos conceptos en inglés y sobre el cual haré un recorrido para explicar en español y en la mayor medida posible con mis palabras su mensaje. Aquí el enlace al texto original:</p><p><a href="https://chunksofco.de/front-end-vs-back-end-vs-client-side-vs-server-side-7a04b3ec8764">https://chunksofco.de/front-end-vs-back-end-vs-client-side-vs-server-side-7a04b3ec8764</a></p><h3>Un salón lleno de ruido</h3><p>Llevo algún tiempo en el proceso de convertirme en desarrollador y tras varios meses de navegar en varias plataformas, tutoriales, clases en vivo y comunidades en twitter o twitch, he visto que este camino es inmenso, con muchas variantes, incontables oportunidades abiertas y fundamentalmente colaborativo y optimista. Sin embargo, también he visto que hay mucho ruido. En ocasiones suelo sentir que ingreso a una sala donde muchos hablan, de todo a la vez, donde quien habla asume muchas veces que los demás saben lo que él sabe y que su punto de vista es evidente para quienes están simultáneamente escuchándolo a él y a otro que habla de lo mismo pero a la vez de otra cosa.</p><p>Ahora, ¿cómo culpar a alguien? En realidad todos están haciendo su esfuerzo más honesto por compartir lo que saben y ayudar a la comunidad en un contexto donde hay muchísimo por aprender. Para transmitir allí algún resultado concreto y explicar cómo fue posible, hay que asumir que se saben varios temas; de lo contrario, sería más costosa la explicación que la tarea en sí y a lo mejor nos encontraríamos es un salón en silencio (¡lo cuál sería peor!).</p><p>Así que habrá que prepararse para entrar a ese salón, construir lenta pero profundamente la base que nos permita ingresar y participar en las conversaciones que nos interesan en relación a nuestros objetivos. Encontrar conversaciones que provean claridad, profundidad, contexto y sentido para avanzar. Al final del día creo que un salón con mucho ruido y en el cual buscamos entrar y encontrar valor aplica como metáfora tanto para estos temas de convertirse en desarrollador como para la vida en general.</p><p>Buscando cómo abordar mejor mi participación en el salón, encontré un artículo espectacular sobre 4 conceptos que son fundamentales para entender cómo opera esto del desarrollo, sea web, mobile o desktop. Quiero compartir los puntos principales en español para guiar a quienes quieren ingresar al salón o quienes ya entraron y se sienten un poco perdidos.</p><h3>¿Cómo funciona la web?</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*un9q7A-Q4AIZAi0tf5ALJQ.png" /><figcaption>Modelo muy muy simplificado del funcionamiento web</figcaption></figure><p>El navegador (browser) es la puerta principal a través de la cuál ingresamos a Internet y existe para que:</p><ol><li>Podamos descargar cosas y mostrarlas en una interfaz bonita, principalmente en forma de página web.</li><li>Enviarle datos a Internet usando formularios, botones, campos de texto, etc., de tal forma que Internet haga su magia y nos conteste con información de nuestro interés.</li></ol><p>Es decir, funcionaría algo así como:</p><ol><li>Ingreso una dirección en el navegador y con eso le estaríamos diciendo a Internet: “Oye, ¿puedes compartirme los datos que se encuentran en esa dirección?”.</li><li>Internet me contesta con “HTML y CSS”. Es decir, con instrucciones para mi navegador a través de las cuales éste me va a mostrar la interfaz bonita que quería ver: “Navegador, aquí están los datos, deberías mostrar una página con fondo blanco, un título centrado en fuente Arial que diga ‘Hola Mundo’ y un párrafo que […]”.</li><li>El navegador descarga esas instrucciones, las lee y las ejecuta para que finalmente yo vea la interfaz.</li><li>Luego, dentro de esa interfaz hay unos campos que yo puedo diligenciar, digamos, para ingresar a mi cuenta. Diligencio los datos y hago click en el botón de ‘Login’.</li><li>Mi navegador toma esos datos y los envía a Internet para que éste haga su magia.</li><li>Internet contesta con más HTML y CSS donde me indica que ingresé satisfactoriamente y me muestra el contenido de mi cuenta.</li><li>Reviso mi cuenta y quiero actualizar mis datos. Actualizo el formulario, hago click en guardar, enviamos datos a Internet, sucede la magia de verlos de nuevo pero ahora con el contenido correcto y así puedo seguir con más.</li></ol><h3>¿Quién hace la magia? El servidor.</h3><p>Internet no es (por lo menos no del todo) intangible y nuestro navegador no habla sólo. Nuestro navegador habla con un servidor, que dicho de forma plana es otro computador que se encuentra conectado a la misma red mundial a la que todos nos conectamos: ‘Internet’. Así que al final del día, Internet es realmente una colección de muchos muchos servidores, los cuales reciben nuestros datos y nos contestan con resultados coherentes luego de computar (procesar) nuestra petición.</p><p>Para el caso anterior, el servidor nos envió los datos de nuestra cuenta, o más precisamente, nos envió los datos que en algún pasado nosotros le dijimos que eran nuestros datos y los cuales ahora vemos están desactualizados. Modificamos aquellos que requieren actualización y al hacer click en ‘guardar’, el servidor aceptará los cambios y no los olvidará. Tanto así que podemos ingresar a nuestra cuenta desde cualquier otro dispositivo y el servidor nos mostrará los datos correctos.</p><p>Ahora, ¡puedo hacer que el servidor haga magia desde cualquier dispositivo! ¿Cómo es eso?</p><h3>¿Quién invoca la magia? El cliente.</h3><p>Dijimos que el navegador pide y el navegador muestra, pero ¿quién es el navegador? Pues es un programa diseñado para comunicarse con servidores en Internet, hacerles peticiones y mostrar las instrucciones que recibe. Se han construido muchos programas con este propósito y su intención es que el usuario pueda invocar la magia de los servidores que conforman Internet desde su PC, Laptop, Smartphone, Notebook, etc.</p><p>En cualquiera de estos dispositivos, si tenemos un navegador, podremos hacer peticiones, interpretar las respuestas que emite el servidor (HTML, CSS, imágenes, videos) y gráficamente observarlas de una forma entendible como usuario. También transmitirá las entradas de datos que hagamos y podremos así fluir en armonía con el servidor para lograr nuestro objetivo al navegar.</p><p>Con esto, es claro que existen dos mundos. El lado del servidor (<em>server-side</em>) y el lado del cliente (<em>client-side</em>). Profundicemos en ellos un poquito.</p><h3>Client-Side vs Server-Side</h3><p>Como si de una comunicación humana se tratara, en un momento hay alguien que habla y otro que escucha. En este contexto, hay momentos donde uno de los lados esta operando y el otro está esperando. Hablamos de <em>client-side </em>y de <em>server-side </em>para separar ambos mundos y clarificar en dónde está ocurriendo una operación determinada.</p><h4>Operaciones client-side</h4><p>Vimos que el navegador (o el software que usemos en cualquier dispositivo para hablar con los servidores de Internet) le envía información al servidor con los datos que nosotros le entregamos y luego traduce las respuestas de éste para nuestro uso. Sin embargo, este software no sólo se dedica a ello, él es también capaz de hacer magia y muchas veces queremos que la haga.</p><p>¿En qué escenario nos gustaría? veamos un ejemplo. Pensemos en la página web de Instagram:</p><ol><li>Ingresamos la URL en el navegador.</li><li>El navegador busca el servidor que contiene la información de esa URL y recibe de él las primeras instrucciones.</li><li>Vemos en pantalla la página de acceso, ingresamos nuestras credenciales y damos click en ‘login’.</li><li>El navegador envía los datos al servidor, el servidor hace su validación y nos regresa las instrucciones con el ‘home’ de nuestra cuenta.</li><li>Queremos subir una foto, así que cargamos alguna que se encuentre almacenada en nuestro dispositivo y ¡en la interfaz la vemos! (¡operación hecha por nuestro navegador!). Tiene un tono algo raro, quiero ponerle un filtro. ¿Quién debería hacer la magia? ¿El servidor?¿El cliente?</li></ol><p>En este punto, podríamos hacer que esta operación fuera<em> server-side</em>. Es decir, enviarle la imagen al servidor para que éste la altere a través de algún programa que modifique las sombras y colores de sus pixeles. Sin embargo, la experiencia del usuario podría ser terrible. Tendría que esperar a que eso sucediera y a que el navegador descargara la nueva imagen para mostrarla con las modificaciones. Así que no, mejor hagamos de esta una operación <em>client-side</em>.</p><p>Damos click en filtros y nuestro navegador, a través de quizá el mismo programa que habría usado el servidor para alterar las imágenes, nos habilitará las opciones y podremos ver rápidamente cómo quedaría la imagen con cada filtro aplicado.</p><p>A medida que nuestros dispositivos van evolucionando y son cada vez más potentes, podemos realizar operaciones<em> client-side</em> más complejas de forma eficiente.</p><h4>Operaciones server-side</h4><p>Es muy normal que las operaciones del lado del servidor sean operaciones de tipo almacenamiento y recuperación de datos. Siguiendo con el ejemplo de Instagram:</p><ol><li>Toda vez que un usuario ingresa y carga una nueva foto, los servidores de Instagram las almacenan en una base de datos, quedando dispuestas para su consumo posterior.</li><li>Si bien es posible que el cliente almacene imágenes y datos, realmente no tiene sentido que almacene todas las fotos y vídeos de todos los perfiles. Una decisión de este estilo sería inviable, pues no hay forma de que un dispositivo de uso individual pudiera almacenar tal volumen de información.</li><li>Por ello, cada vez que queremos consultar un perfil debemos esperar algún tiempo hasta que logramos descargar la información que el servidor nos entrega en relación a ese perfil. Este tiempo será el que le tome al servidor el buscar entre millones de usuarios y fotos para encontrar aquel que solicitamos.</li></ol><p>Hay más operaciones que podrían realizarse del lado del servidor aparte de esta operación de búsqueda. Sin embargo, lo importante aquí es entender la separación <em>server-side</em> vs. <em>client-side</em>. El equipo de desarrollo deberá decidir de qué lado se ejecutará cada operación basándose en las restricciones del proceso de cómputo y en entregar la mejor experiencia al usuario.</p><p>Esto aplica no sólo para el navegador como tal, sino que también le aplica a las aplicaciones móviles o desktop que se están ejecutando en el dispositivo del cliente y que deben interactuar con el lado del servidor para en conjunto atender las necesidades del usuario. Es decir, aquí asumimos que ingresábamos al sitio web de Instagram para cargar la foto, pero lo mismo aplica si abrimos la app desde nuestro celular.</p><p>Con lo anterior, tenemos más claro que por qué existe la comunicación entre el <em>client-side</em> y el <em>server-side</em> y que habrá algunas operaciones que se ejecuten en un lado y otras en el otro. Ahora, al final siempre hay que llegar a una conclusión, es decir, al final ambos mundos deben conectarse, concluir sus operaciones y comunicaciones y terminar con una interfaz usable. A esta conclusión le llamamos ‘Rendering’.</p><h3>Rendering</h3><h4>¿Qué es rendering?</h4><p>Para el contexto específico del que estamos hablando, ‘rendering’ es la combinación de datos con HTML y CSS para ser mostrados en la interfaz.</p><p>Si entras a Instagram, verás tu foto de perfil, nombre y usuario en una sección de la interfaz, además de ver las historias y últimas publicaciones de las personas que sigues. Todos estos datos como dijimos existen y se almacenan en el servidor pero para que el usuario pueda verlos de forma bonita y clara en la pantalla, estos datos deben combinarse con HTML y CSS y así lograr su presentación.</p><p>Si cerramos sesión y otra persona ingresa con su cuenta, verá el mismo ‘layout’ o estructura visual, pero su contenido, sus datos, serán relativos a su cuenta y a los usuarios a quién ella sigue.</p><p><strong>Este proceso de tomar los datos relevantes y combinarlos con HTML y CSS para que el navegador entienda qué es lo que debe mostrar es lo que definimos como ‘render’.</strong></p><p>En línea con lo que vimos antes, ‘renderizar’ es en sí misma una operación, así que debemos decidir dónde la haremos. ¿En el lado del servidor?¿En el lado del cliente?</p><h4>Server-side rendering</h4><p>Decidir que el rendering se haga del lado del servidor significa que será él quien combine los datos con el HTML y el CSS para definir cómo debería ser presentada la información al usuario. Los desarrolladores deberán desarrollar código para el servidor de tal forma que este pueda recuperar los datos de su base de datos, unirlos con la estructura del HTML y CSS y enviarlos al navegador para ser presentados.</p><p>Si decidimos hacerlo del lado del cliente, necesitaremos una capacidad homóloga de ejecutar código y hacer que esa unión de datos con HTML y CSS funcione. ¿Cómo lo haríamos?</p><h4>Introducción a JavaScript</h4><p>Los navegadores no sólo entienden de HTML y CSS, también entienden de JavaScript; un lenguaje de programación que nos permitirá ejecutar instrucciones que le den vida a la web.</p><p>JavaScript es genial en este caso porque:</p><ol><li>Podemos usarlo para manipular datos, HTML y CSS. Es decir, podemos transformar con JavaScript la forma en que la página es mostrada al usuario luego de haber cargado lo que nos retornó el servidor.</li><li>JavaScript puede lograr lo anterior porque deliberadamente el desarrollador así lo define o porque el usuario puede decidirlo durante su interacción con la web (clicks, entradas de texto, movimientos del mouse, comandos de teclado). Podemos deslizar imágenes, ocultar o resaltar texto, desplegar menús y más sin necesidad de solicitarle al servidor un nuevo HTML y CSS.</li><li>Lo último es muy interesante, pues significa que el navegador no depende 100% del servidor para obtener las instrucciones que debe ejecutar a la hora de interactuar con el usuario. El servidor originalmente puede enviar algún código en JavaScript en conjunto con el HTML y CSS y con ello no tener que enviar más información durante un tiempo, pues el navegador se encargará de ejecutar ciertas operaciones.</li><li>Es decir, podemos usar JavaScript para divertirnos del lado del cliente 👌.</li></ol><h4>¿Por qué querríamos evitar hacer peticiones al servidor?</h4><p>Cada vez que el navegador solicita información al servidor, debemos esperar un tiempo hasta que se transmite esa petición, se ejecuta en el servidor, se transporta la respuesta y la descargamos.</p><p>Además, la experiencia de usuario podría ser mucho más ágil si sólo solicitamos datos al servidor y no datos junto con información de la interfaz. Los datos son relativamente ligeros en comparación con la descarga de datos más HTML y CSS.</p><h4>Client-side rendering</h4><p>Así que tenemos esta posibilidad abierta respecto al ‘rendering’. Podríamos decidir hacer render del lado del cliente y usar JavaScript para lograrlo. Como siempre, será el diseño y el criterio del equipo desarrollador quien lo decida, teniendo siempre como objetivo optimizar la experiencia del usuario.</p><p>Hasta aquí hemos simplificado cómo funciona la web y cómo nos conectamos con ella, hemos hablado sobre la existencia de operaciones del lado del cliente (<em>client-side</em>) y del lado del servidor (<em>server-side</em>), las cuales en conjunto logran mostrarle al usuario una interfaz con la cual puede interactuar y obtener los resultados deseados.</p><p>Pero, en todo esto no hemos hablado de ¿qué significa hablar de front-end o de back-end? y ¡está en el título de este artículo! ¿tienen estos conceptos alguna relación con lo que ya vimos?¿son cosas diferentes? Miremos.</p><h3>Front-end vs. Back-end</h3><p>Empecemos por mencionar que es muy común encontrar que se igualen estos dos términos con aquellos que vimos anteriormente: <em>client-side</em> y <em>server-side</em>. Es decir, suele usarse el término <em>front-end</em> como si fuera exactamente igual a decir <em>client-side</em> y que hablar de <em>back-end</em> es igual a hablar de <em>server-side</em>. Cada pareja sí tiene mucho en común, pero también existen diferencias. Veamos de qué se trata:</p><h4>¿Qué significa front-end?</h4><p>Hablar de <em>front-end</em> es habar de todo aquello que esté relacionado con la interfaz de usuario y su experiencia. Un desarrollador <em>front-end</em> escribe código para construir la interfaz del usuario y con ella ofrecerle una experiencia grata y efectiva. En términos prácticos, además de tener dentro de su campo de conocimiento uno o varios lenguajes de programación (usualmente JavaScript por aquello que conversamos del navegador) debe de entender de HTML y CSS.</p><p>Bien podríamos haber decidido, como lo revisamos antes, que el ‘rendering’ de la aplicación fuera <em>server-side</em>. Sin embargo, es el desarrollador <em>front-end</em> quien debe de escribir el HTML y CSS que se va a ‘renderizar’, así sea en el servidor, para luego ser enviado al cliente. En este caso deberá trabajar del lado del servidor para lograrlo.</p><p>Por el contrario, si decidimos hacer ‘render’ en el <em>client-side</em>, pues allí también participará activamente el desarrollador <em>front-end</em> para construir el HTML, CSS y JavaScript que sea necesario para la interfaz deseada.</p><p>Es normal que a la hora de construir estas interfaces, muchas soluciones a problemas del desarrollo se repitan. También es normal que nadie desee resolver una y otra vez desde cero los mismos problemas en cada proyecto (barras de navegación, formularios de login, carritos de compras y muchos otros). Para ello, desarrolladores, equipos o comunidades de desarrollo construyen librerías o si se quiere más, <em>frameworks</em>, donde estos problemas estén resueltos con mucho detalle y con mayor proceso de maduración, de tal forma que no sea necesario reinventar una solución cada vez que se necesita. Estas librerías o estos <em>frameworks </em>(<a href="https://www.youtube.com/watch?v=yC6wR3szGz8">no son lo mismo, cuidado</a>), pueden encontrarse en el entorno como ‘<em>front-end frameworks</em>’ y resultan muy útiles porque agilizan la construcción de soluciones, han madurado mucho más que las soluciones que uno pudiera inventar por su propia cuenta y es más factible predecir su comportamiento dentro de una aplicación dadas las experiencias pasadas en su uso.</p><p>Ejemplos muy conocidos de lo anterior son: <a href="https://reactjs.org/">React</a>, <a href="https://vuejs.org/">Vue</a> y <a href="https://angular.io/">Angular</a>.</p><h4>¿Qué significa back-end?</h4><p>Como complemento de lo anterior, <em>back-end</em> será todo aquello que sí, sucede del lado del servidor, pero que no está relacionado directamente con la interfaz de usuario. Allí estaríamos hablando en general del almacenamiento, procesamiento, consulta y entrega de datos que luego serán usados en el <em>render </em>de la web. Su fuerte deberá ser la capacidad de soportar el hecho de que habrá muchos clientes conectados a los servidores intentando obtener los datos necesarios para lo que sea que el usuario esté haciendo en cada interfaz. Así que deberá lidiar con la concurrencia y el volumen de operaciones garantizando alta disponibilidad, capacidad de procesamiento y seguridad.</p><h3>Conclusión</h3><p>De todos los temas que mencioné previamente se habla en ese salón lleno de personas que les apasiona el desarrollo y que buscan compartir lo que saben y lo que han hecho con ello. No te asustes, habrá mil conversaciones en paralelo y no tienes que participar en todas ellas. Busca aquellas que iluminen tu camino y te permitan tanto entender el panorama como profundizar en lo que has aprendido en conversaciones pasadas. En mi opinión, es preferible profundizar que esparcirse, pues lo primero te permitirá traducir lo que vas aprendiendo en soluciones reales y eso te dará el impulso para seguir entrando al salón.</p><p>Como contenido, la magia de la que disfrutamos todos los días consiste en una comunicación ágil y coherente entre nuestro dispositivo con el software que instalamos en él como ‘software cliente’ y los servidores que hacen parte de esta inmensa red llamada Internet. Con ello construimos y transformamos las interfaces con las cuales almacenamos, procesamos y obtenemos información y así conseguir los resultados que deseamos.</p><p>Para lograr lo anterior, requerimos un profundo trabajo en cuanto a interfaz y experiencia de usuario (<em>front-end</em>) y una respuesta segura, consistente y disponible de la información (<em>back-end</em>).</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4c36b82a550d" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>