<?xml version="1.0" encoding="utf-8"?>
<?xml-stylesheet type="text/css" media="screen" href="/stylesheets/atom.css"?>
<feed xmlns="http://www.w3.org/2005/Atom">

  <title>simonewebdesign</title>
  <link href="https://simonewebdesign.it/atom.xml" rel="self"/>
  <link href="https://simonewebdesign.it/"/>
  <updated>2025-10-12T18:18:40+00:00</updated>
  <id>https://simonewebdesign.it/</id>
  <author>
    <name>Simone Vittori</name>
    
  </author>

  
  <entry>
    <title type="html"><![CDATA[How to make an HTML element keyboard focusable]]></title>
    <link href="https://simonewebdesign.it/how-to-make-an-element-keyboard-focusable/"/>
    <updated>2025-05-13T00:00:00+00:00</updated>
    <id>https://simonewebdesign.it/how-to-make-an-element-keyboard-focusable</id>
    <content type="html"><![CDATA[<p>If you have an HTML element that you want to make interactive, but <strong>only via the keyboard</strong>, there might be a few ways to achieve it, depending on your objective.</p>

<h2 id="using-tabindex0"><a href="#using-tabindex0">Using <code class="language-plaintext highlighter-rouge">tabindex="0"</code></a></h2>

<p><a href="https://developer.mozilla.org/en-US/docs/Web/HTML/Reference/Global_attributes/tabindex">Tabindex</a> is an HTML attribute that makes HTML elements <em>tabbable</em>—as in, focusable by pressing <kbd>Tab</kbd>.</p>

<p>It’s primarily intended to <a href="https://developer.mozilla.org/en-US/docs/Web/Accessibility/Guides/Understanding_WCAG/Keyboard">enhance accessibility</a>. However, if you find yourself needing to use it, consider whether a more semantic, inherently <strong>interactive element</strong>—like a <code class="language-plaintext highlighter-rouge">&lt;button&gt;</code> or an <code class="language-plaintext highlighter-rouge">&lt;a&gt;</code>—might be more appropriate. These elements are <strong>naturally focusable</strong> and better communicate intent to users and assistive technologies.</p>

<h2 id="using-tabindex-1"><a href="#using-tabindex-1">Using <code class="language-plaintext highlighter-rouge">tabindex="-1"</code></a></h2>

<p>This is the other allowed value of <code class="language-plaintext highlighter-rouge">tabindex</code> (anything other than <code class="language-plaintext highlighter-rouge">0</code> and <code class="language-plaintext highlighter-rouge">-1</code> is discouraged), and it’s used to make an element focusable, but only programmatically (i.e. via JavaScript).</p>

<p>In practice this makes the element no longer tabbable, but actually it <strong>can still be focused via a mouse click</strong>, in some browsers.</p>

<h2 id="using-pointer-events-none"><a href="#using-pointer-events-none">Using <code class="language-plaintext highlighter-rouge">pointer-events: none;</code></a></h2>

<p>This CSS rule will disable any kind of interactivity via <em>pointers</em> (e.g. a mouse click, or a tap on mobile), but will retain the ability to focus the interactive element via the keyboard.</p>

<p>However, it might have unintended consequences: let’s say your element has a <code class="language-plaintext highlighter-rouge">title</code> attribute, which you’d like to display on mouse hover: with <code class="language-plaintext highlighter-rouge">pointer-events: none</code>, this won’t work anymore.</p>

<h2 id="how-to-prevent-click-focusing-via-javascript"><a href="#how-to-prevent-click-focusing-via-javascript">How to prevent click focusing via JavaScript</a></h2>

<p>If you want to focus your element only via JavaScript, and prevent click focusing, one reliable approach is to intercept mouse events (on the element itself):</p>

<div class="language-js highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="nx">element</span><span class="p">.</span><span class="nf">addEventListener</span><span class="p">(</span><span class="dl">'</span><span class="s1">mousedown</span><span class="dl">'</span><span class="p">,</span> <span class="nx">event</span> <span class="o">=&gt;</span> <span class="p">{</span>
  <span class="nx">event</span><span class="p">.</span><span class="nf">preventDefault</span><span class="p">()</span>
<span class="p">})</span>
</code></pre></div></div>

<p>This works because preventing the mousedown event stops the browser from giving the element focus when clicked.</p>

<p>You’ll then need to focus your element manually, by listening for a key press.</p>

<h2 id="full-example"><a href="#full-example">Full example</a></h2>

<p>If what you want is an element that can be focused programmatically, but <strong>only via a specific key, and not by a mouse click</strong>, here’s a full working example:</p>

<div class="language-html highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="nt">&lt;div</span> <span class="na">id=</span><span class="s">"myDiv"</span> <span class="na">tabindex=</span><span class="s">"-1"</span><span class="nt">&gt;</span>Focus me<span class="nt">&lt;/div&gt;</span>

<span class="nt">&lt;script&gt;</span>
  <span class="kd">const</span> <span class="nx">el</span> <span class="o">=</span> <span class="nb">document</span><span class="p">.</span><span class="nf">getElementById</span><span class="p">(</span><span class="dl">'</span><span class="s1">myDiv</span><span class="dl">'</span><span class="p">)</span>

  <span class="nx">el</span><span class="p">.</span><span class="nf">addEventListener</span><span class="p">(</span><span class="dl">'</span><span class="s1">mousedown</span><span class="dl">'</span><span class="p">,</span> <span class="nx">e</span> <span class="o">=&gt;</span> <span class="p">{</span>
    <span class="nx">e</span><span class="p">.</span><span class="nf">preventDefault</span><span class="p">()</span> <span class="c1">// Prevent focus on click</span>
  <span class="p">})</span>

  <span class="c1">// You can still focus it programmatically,</span>
  <span class="c1">// for example by listening for a key press</span>
  <span class="nb">document</span><span class="p">.</span><span class="nx">body</span><span class="p">.</span><span class="nf">addEventListener</span><span class="p">(</span><span class="dl">'</span><span class="s1">keydown</span><span class="dl">'</span><span class="p">,</span> <span class="nx">event</span> <span class="o">=&gt;</span> <span class="p">{</span>
    <span class="k">if </span><span class="p">(</span><span class="nx">event</span><span class="p">.</span><span class="nx">key</span><span class="p">.</span><span class="nf">toLowerCase</span><span class="p">()</span> <span class="o">===</span> <span class="dl">'</span><span class="s1">f</span><span class="dl">'</span><span class="p">)</span> <span class="p">{</span> <span class="c1">// only true when pressing 'F'</span>
      <span class="nx">el</span><span class="p">.</span><span class="nf">focus</span><span class="p">()</span>
    <span class="p">}</span>
  <span class="p">})</span>
<span class="nt">&lt;/script&gt;</span>
</code></pre></div></div>

<p>The example above has a <code class="language-plaintext highlighter-rouge">&lt;div&gt;</code> that is:</p>

<ul>
  <li>❌ Not tabbable;</li>
  <li>❌ Not clickable;</li>
  <li>✅ Focusable (via key press).</li>
</ul>

<p>Feel free to check out <a href="https://codepen.io/simone/pen/WbbLYEX">this pen</a> for a live example.</p>

<hr />

<p>Hopefully this lets you achieve what you want, but let me know if you’re targeting a specific element type or browser; I’ll be happy to help.</p>

<p>Happy hacking!</p>
]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[A Programming Love Letter]]></title>
    <link href="https://simonewebdesign.it/programming-love-letter/"/>
    <updated>2025-03-28T00:00:00+00:00</updated>
    <id>https://simonewebdesign.it/programming-love-letter</id>
    <content type="html"><![CDATA[<!-- I tried writing this post before, but felt it was a bit too corny. Regardless, I decided to revamp it and share it anyway. Some of you may find it inspiring, perhaps. -->

<p>Think a little about why you enjoy what you enjoy.</p>

<p>Why do you code? What do you like about it? I’ve been asking myself these questions, but I haven’t quite found the answer yet. Maybe there’s no single answer, after all. For me, it’s an <em>ensemble</em>; there’s a whole range of reasons that make programming so enticing to me. For example, I feel like…<!--more--></p>

<ul>
  <li>
    <p><strong>Programming is like writing a poem.</strong> A beautiful set of words that fit well together; ideally short &amp; sweet. Finding the right balance is tricky, but very rewarding once you do.</p>
  </li>
  <li>
    <p><strong>Programming is like solving a puzzle.</strong> Each piece has its own place, and the satisfaction of fitting them all together can be immensely gratifying. The most experienced developers realise there’s often a plethora of solutions to the same problem, and finding that perfect fit can be just as rewarding as solving a tricky challenge.</p>
  </li>
  <li>
    <p><strong>Programming is like painting.</strong> Paul Graham wrote <a href="http://www.paulgraham.com/hp.html">a whole essay</a> about it. <em>Hackers and Painters</em> have so much in common, indeed. They’re both <strong>makers</strong>; they want to make their masterpiece, and every little detail matters just as much as the big picture.</p>
  </li>
  <li>
    <p><strong>Programming is like an indoor plant</strong>. You nurture it, cut here and there from time to time. Refactoring code is a bit like caring for a bonsai tree: the branches you cut might grow back stronger.</p>
  </li>
  <li>
    <p><strong>Programming is like building an airplane</strong>. It has to be lean and fast, so the less it carries, the better. Less is more; you know it’s ready to fly when you removed as much as you could, and there’s nothing else to add.</p>
  </li>
  <li>
    <p><strong>Programming is a fun activity.</strong> I love spending hours every day thinking about solutions to problems—sometimes my own, sometimes other people’s—I just find it fun and exciting. Being able to <strong>create</strong> something from a blank slate, is what inspires me the most.</p>
  </li>
</ul>

<p>Ultimately, coding is much more than a technical skill; it’s a way of thinking that can permeate through every aspect of your life.</p>

<p>What inspires you to code?</p>
]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[A Modern Slave Society Blueprint (ChatGPT transcript)]]></title>
    <link href="https://simonewebdesign.it/modern-slave-society-blueprint/"/>
    <updated>2024-12-28T00:00:00+00:00</updated>
    <id>https://simonewebdesign.it/modern-slave-society-blueprint</id>
    <content type="html"><![CDATA[<p>After blogging on and off for 12 years about tech-related topics, I felt it was time for a change.</p>

<p>Since <a href="https://gomakethings.com/i-follow-you-for-tech-not-politics/">all tech is political</a>, with this article I aim to explore critical issues such as systems of social control, ethics and freedom, while offloading all of the “thinking” to a computer, in order to avoid my own personal biases.</p>

<p>I’m writing this at a time when <abbr title="Artificial Intelligence">AI</abbr> is disrupting society and the world as we know it—and I don’t mean <em>disrupting</em> in the Silicon Valley start-up sense; I mean it <em>literally</em>.<!--more--></p>

<blockquote>
  <p><strong>disrupt</strong> <em>/dĭs-rŭpt′/</em>
<br /><small>transitive verb</small></p>
  <ol>
    <li>To throw into confusion or disorder.<br />
<small>“Protesters disrupted the candidate’s speech.”</small></li>
    <li>To interrupt or impede the progress of.<br />
<small>“Our efforts in the garden were disrupted by an early frost. The noise disrupted my nap.”</small></li>
    <li>To break apart or alter so as to prevent normal or expected functioning.<br />
<small>“radiation that disrupts <abbr title="Deoxyribonucleic acid">DNA</abbr> and kills bacteria.”</small>
<br /><br /><cite>—The American Heritage® Dictionary of the English Language, 5th Edition</cite></li>
  </ol>
</blockquote>

<p>I’ve asked ChatGPT some interesting questions, and the answers were also very interesting, so I thought I’d post the full conversation on here. The rest of this article is the full, unaltered transcript of my conversation with the <abbr title="Artificial Intelligence">AI</abbr> (GPT-4o).</p>

<hr />

<h2 id="prompt">Prompt:</h2>

<p>if you had to create a modern society where the vast majority of people are slaves, but they don’t realise it… what would you do?</p>

<h2 id="chatgpt-said">ChatGPT said:</h2>

<p>Creating a society where the vast majority of people are effectively enslaved without realizing it would require a carefully crafted system of control. The aim would be to ensure that people feel free, while their choices, desires, and perceptions are manipulated to serve the interests of the ruling class. Here’s a blueprint for how such a society could be constructed:</p>

<h3 id="1-economic-dependency-masquerading-as-freedom">1. <strong>Economic Dependency Masquerading as Freedom</strong></h3>

<p><strong>Strategy</strong>: Create an economy that demands perpetual labor but frames it as personal choice and opportunity.</p>

<ul>
  <li><strong>Debt as a Tool of Control</strong>: Ensure that people are burdened with debt early in life (e.g., through student loans, housing, and consumerism). Make it seem necessary to work for decades to pay off these debts, presenting this as a natural part of adulthood and ambition.</li>
  <li><strong>Wage Slavery</strong>: Offer wages that are just high enough to survive but low enough to keep people in a constant cycle of work. Raise the cost of living through inflation and market-driven prices, ensuring that working longer hours feels like personal advancement.</li>
  <li><strong>Gig Economy</strong>: Promote “entrepreneurial” opportunities like freelancing or gig work as freedom, while denying workers the benefits and protections of traditional employment, creating instability masked as flexibility.</li>
</ul>

<h3 id="2-social-control-through-entertainment-and-distraction">2. <strong>Social Control Through Entertainment and Distraction</strong></h3>

<p><strong>Strategy</strong>: Flood the population with constant entertainment, ensuring they are too distracted to question the system.</p>

<ul>
  <li><strong>Media Saturation</strong>: Provide endless streams of entertainment, from social media to video games and TV shows, that keep people engaged in trivial pursuits. Make this content algorithmically tailored to individual preferences to maintain constant engagement.</li>
  <li><strong>Culture of Celebrity and Consumerism</strong>: Promote celebrities, influencers, and brands as aspirational figures. Encourage people to measure success through material wealth, lifestyle, and social status. This keeps people focused on consumption rather than critical thinking.</li>
  <li><strong>Bread and Circuses</strong>: Offer constant distractions through entertainment events (sports, reality TV, etc.), social media challenges, and viral content. This maintains a cycle of superficial engagement, keeping the deeper problems of society hidden.</li>
</ul>

<h3 id="3-perceived-freedom-through-illusion-of-choice">3. <strong>Perceived Freedom Through Illusion of Choice</strong></h3>

<p><strong>Strategy</strong>: Create a system where people believe they are making choices, but the options presented always benefit the controlling powers.</p>

<ul>
  <li><strong>Rigged Political Systems</strong>: Maintain the illusion of democracy by offering multiple political parties or candidates, but ensure that the policies of any elected officials are largely controlled by corporate or elite interests. Limit actual change by having the political system structured to preserve the status quo.</li>
  <li><strong>False Choices in Consumerism</strong>: Provide people with an abundance of choices in the marketplace (brands, products, services), but ensure that these choices serve the same economic interests, further deepening their dependence on consumption.</li>
</ul>

<h3 id="4-control-of-information-and-education">4. <strong>Control of Information and Education</strong></h3>

<p><strong>Strategy</strong>: Manipulate education and information flow to shape perception and prevent critical thinking.</p>

<ul>
  <li><strong>Educational Indoctrination</strong>: Design the education system to emphasize compliance, memorization, and career readiness over critical thinking or questioning authority. Normalize standardized testing and narrow curricula to prevent broader intellectual exploration.</li>
  <li><strong>Censorship Through Oversaturation</strong>: Instead of restricting information, overwhelm people with too much data—real, fake, biased, neutral—making it difficult for the average person to discern truth from fiction. Distract with conspiracy theories, trivial news, and fearmongering.</li>
  <li><strong>Historical Amnesia</strong>: Frame historical events and power dynamics in ways that downplay oppression and revolution. Present society as the culmination of progress where drastic change is unnecessary or dangerous.</li>
</ul>

<h3 id="5-psychological-control-and-identity-management">5. <strong>Psychological Control and Identity Management</strong></h3>

<p><strong>Strategy</strong>: Manipulate people’s understanding of themselves and their place in society so they remain compliant.</p>

<ul>
  <li><strong>Cult of Individualism</strong>: Promote the idea that personal success is solely dependent on individual effort. This creates a culture where systemic issues (inequality, injustice) are framed as personal failures. Individuals feel shame rather than questioning societal structures.</li>
  <li><strong>Fear of the Other</strong>: Use division to keep people distracted. Pit social groups against one another (e.g., through race, gender, class, or political affiliations), ensuring that people see each other as threats rather than allies against a shared system of control.</li>
  <li><strong>Mental Health Manipulation</strong>: Normalize the treatment of systemic stress (overwork, isolation, alienation) as individual mental health issues. Encourage people to seek self-help solutions (therapy, meditation apps, pharmaceuticals) rather than addressing the root causes of their dissatisfaction.</li>
</ul>

<h3 id="6-surveillance-and-data-exploitation">6. <strong>Surveillance and Data Exploitation</strong></h3>

<p><strong>Strategy</strong>: Gather data on individuals to predict and shape their behavior without them realizing the extent of the control.</p>

<ul>
  <li><strong>Voluntary Surveillance</strong>: Encourage the use of personal devices (smartphones, wearables) that track and monitor individuals. Frame this as convenience or personal improvement (fitness apps, location services, etc.), but use the data to predict and manipulate behavior, preferences, and even political opinions.</li>
  <li><strong>Social Credit and Rating Systems</strong>: Implement subtle systems where people are rated or ranked based on their behavior (similar to a social credit system). Use algorithms to shape people’s online experiences, influencing what they see, hear, and believe. Over time, people’s behavior can be gently nudged towards compliance.</li>
  <li><strong>Normalization of Surveillance</strong>: Make public surveillance (cameras, facial recognition) a natural part of daily life under the guise of safety and security. Most people will accept the loss of privacy if it’s positioned as protecting them from vague threats like terrorism or crime.</li>
</ul>

<h3 id="7-normalization-of-work-and-status-quo">7. <strong>Normalization of Work and Status Quo</strong></h3>

<p><strong>Strategy</strong>: Make hard work and compliance feel like personal virtues, where questioning the system feels dangerous or ungrateful.</p>

<ul>
  <li><strong>Work as Identity</strong>: Encourage a culture where people derive their sense of identity and worth from their careers and productivity. This not only keeps people working longer but also prevents them from seeing their labor as exploitation.</li>
  <li><strong>“Self-Help” Ideology</strong>: Push narratives of self-improvement, framing systemic inequalities as personal development challenges. People are less likely to revolt if they believe their struggles are due to their own failure to work hard enough or “hustle” sufficiently.</li>
  <li><strong>Status Quo as Sacred</strong>: Teach people to view the current system as the best possible arrangement. Anyone who questions or criticizes it is painted as dangerous or radical. Use media to discredit any alternatives to the system as impractical or harmful.</li>
</ul>

<h3 id="8-perpetual-crisis">8. <strong>Perpetual Crisis</strong></h3>

<p><strong>Strategy</strong>: Keep society in a state of controlled crisis, where fear and uncertainty prevent people from organizing or seeking change.</p>

<ul>
  <li><strong>Threat of External Enemies</strong>: Constantly present external or internal enemies (other countries, immigrants, terrorists, hackers) to justify the expansion of control measures. Fear keeps people in line and makes them more willing to accept restrictions on their freedom.</li>
  <li><strong>Artificial Scarcity</strong>: Engineer or exaggerate shortages (resources, energy, housing) to create competition among the populace. When people are focused on personal survival, they are less likely to unite against systemic oppression.</li>
  <li><strong>Perpetual Crisis Mode</strong>: Maintain a cycle of emergencies (economic, health, political) that prevent people from feeling stable enough to question the system. Crises, whether real or manufactured, can justify authoritarian responses and tighter controls.</li>
</ul>

<hr />

<h3 id="conclusion">Conclusion</h3>

<p>This hypothetical society would combine economic, psychological, and informational control to create an environment where people are technically free but in practice are enslaved to the system. The key would be ensuring that the illusion of freedom is maintained, that people believe their hardships are personal rather than systemic, and that they remain too distracted or fearful to seek change.</p>

<p><br /></p>

<h2 id="prompt-1">Prompt:</h2>

<p>What would the deepest problems be in this hypothetical modern society that is full of slavery?</p>

<h2 id="chatgpt-said-1">ChatGPT said:</h2>

<p>In this hypothetical society where slavery is deeply embedded, yet unrecognized by most of the population, the underlying problems would be profound and multifaceted. While the majority of people may not be overtly aware of their subjugation, the system would be rife with contradictions and unsustainable dynamics. These problems would affect not only the individuals enslaved within the system but the very structure of society itself.</p>

<h3 id="1-psychological-alienation-and-identity-crisis">1. <strong>Psychological Alienation and Identity Crisis</strong></h3>

<ul>
  <li><strong>Loss of Authentic Self</strong>: Individuals in this society would likely experience deep feelings of alienation. They would be conditioned to believe they are “free,” but their lives would be driven by forces beyond their control—debt, social expectations, surveillance, and consumption. This creates a crisis of identity, where people may feel disconnected from their true desires or values, living lives defined by external pressures rather than internal fulfillment.</li>
  <li><strong>Existential Frustration</strong>: People would struggle with the sense that their hard work, sacrifices, and aspirations are all directed toward ends that do not truly serve them. This could lead to a rise in mental health issues like depression, anxiety, and burnout, as individuals realize, even subconsciously, that they are trapped in a cycle they cannot break.</li>
</ul>

<h3 id="2-social-division-and-fragmentation">2. <strong>Social Division and Fragmentation</strong></h3>

<ul>
  <li><strong>Class and Economic Stratification</strong>: Even though everyone is technically a “slave” in some sense, there would still be a rigid class divide between the elites (the true masters of the system) and the rest. The lower classes would struggle to meet basic needs, while a wealthy minority would control vast resources. This stratification would foster resentment, inequality, and a sense of powerlessness among those at the bottom, further dividing society.</li>
  <li><strong>Cultural and Social Fragmentation</strong>: The “divide and conquer” strategy—through race, gender, and other social identities—would create deep cultural and social fragmentation. People would feel disconnected from one another, as each group becomes pitted against others, leading to heightened tensions, distrust, and inability to form collective bonds or movements that could challenge the system.</li>
</ul>

<h3 id="3-erosion-of-trust-and-cooperation">3. <strong>Erosion of Trust and Cooperation</strong></h3>

<ul>
  <li><strong>Loss of Community</strong>: In a society where individualism and consumerism are glorified, genuine social connections would deteriorate. People would view each other more as competitors than as fellow human beings. The erosion of trust—both on personal and institutional levels—would hinder any collective effort to resist the system, making it harder for individuals to organize or even empathize with one another.</li>
  <li><strong>Corruption and Exploitation</strong>: Those in positions of power (whether political, corporate, or even within communities) would exploit the system for personal gain, further compounding the inequality. Corruption would become normalized, and the moral fabric of society would weaken. Those in power might use their influence to maintain the illusion of freedom, making it harder for any dissenting voices to be heard or taken seriously.</li>
</ul>

<h3 id="4-deterioration-of-the-environment">4. <strong>Deterioration of the Environment</strong></h3>

<ul>
  <li><strong>Unsustainable Consumption</strong>: A society that encourages endless consumption would rapidly exhaust natural resources, leading to environmental degradation. This could include climate change, deforestation, pollution, and the destruction of ecosystems, all of which would disproportionately affect the poorest, who have the least ability to shield themselves from environmental collapse.</li>
  <li><strong>Overproduction and Waste</strong>: In the name of profit, industries would prioritize overproduction, creating more goods than the population could use. This would lead to enormous amounts of waste, while valuable resources like clean air, water, and fertile soil become scarcer. The cycle of overconsumption and wastefulness would strain both human and environmental systems.</li>
</ul>

<h3 id="5-technological-overreach-and-privacy-violations">5. <strong>Technological Overreach and Privacy Violations</strong></h3>

<ul>
  <li><strong>Surveillance State</strong>: The constant monitoring of individuals’ activities—through data collection, facial recognition, and behavior prediction—would create an environment where privacy is virtually nonexistent. People might become hyper-aware of being watched, but feel powerless to stop it, leading to a society of conformity and self-censorship. This constant surveillance would also be used to suppress dissent and maintain control.</li>
  <li><strong>Technological Dependence</strong>: As the majority of people become increasingly dependent on technology—whether for work, social interaction, or entertainment—they would lose the ability to function without it. A breakdown in technological infrastructure could cripple the whole society, revealing how fragile the system is.</li>
</ul>

<h3 id="6-diminished-critical-thinking-and-intellectual-stagnation">6. <strong>Diminished Critical Thinking and Intellectual Stagnation</strong></h3>

<ul>
  <li><strong>Suppression of Dissent</strong>: In a system where critical thought is seen as a threat to the established order, intellectual creativity and innovation would be stifled. People would be taught to follow orders rather than challenge authority. This would hinder social, technological, and political progress, trapping society in a loop of stagnation.</li>
  <li><strong>Education as Indoctrination</strong>: Rather than cultivating independent thinkers, the education system would function primarily to produce compliant workers. Knowledge would be filtered and controlled to serve the interests of the ruling elites, keeping the population uninformed or misinformed. This would prevent any real social or political evolution, keeping the population docile and uncritical.</li>
</ul>

<h3 id="7-systemic-unfairness-and-injustice">7. <strong>Systemic Unfairness and Injustice</strong></h3>

<ul>
  <li><strong>Legal and Political Disempowerment</strong>: The legal and political systems would serve the interests of the ruling class, ensuring that the majority of people remain disempowered. Laws would be designed to perpetuate inequality, and political reforms would be more about maintaining control than about making genuine changes. People would live in a state of continuous disillusionment, knowing that the system is unjust but unable to change it.</li>
  <li><strong>Criminalization of Resistance</strong>: Any attempt to challenge the system, whether through protest, civil disobedience, or direct action, would be criminalized and harshly punished. Laws would be manipulated to target dissidents, and the state would maintain a monopoly on violence. Dissenters would be labeled as “dangerous” or “radicals,” making it difficult to rally popular support for meaningful change.</li>
</ul>

<h3 id="8-health-crises-and-societal-illness">8. <strong>Health Crises and Societal Illness</strong></h3>

<ul>
  <li><strong>Physical and Mental Health Decline</strong>: In a society of controlled exploitation, the physical and mental health of the population would deteriorate. Overwork, poor nutrition, lack of sleep, and chronic stress would lead to widespread health issues. Mental health crises would become endemic, as people are pushed to their limits both economically and socially. However, these issues might be framed as individual failures or deficiencies, not as symptoms of a broken system.</li>
  <li><strong>Medical Industry as Profiteer</strong>: Healthcare would likely be commodified, where access to quality medical care would be a privilege for the wealthy, while the rest would be subjected to a subpar system designed more to profit from illness than to heal people. This could result in widespread preventable diseases and untreated mental health conditions.</li>
</ul>

<h3 id="9-moral-decay-and-loss-of-empathy">9. <strong>Moral Decay and Loss of Empathy</strong></h3>

<ul>
  <li><strong>Desensitization to Suffering</strong>: In a system where people are conditioned to view others as competitors, the inherent value of human life would be diminished. People might become numb to the suffering of others, seeing it as a natural consequence of the system. This moral decay would create a society that is less compassionate and more callous, where helping others becomes an exception rather than the rule.</li>
  <li><strong>Disconnection from the Global Community</strong>: As people become more isolated in their individual struggles, they would lose sight of their collective humanity. Global issues like poverty, human rights abuses, and climate change would be seen as distant problems, affecting “other” people, rather than an urgent crisis requiring immediate action.</li>
</ul>

<h3 id="conclusion-1">Conclusion</h3>

<p>The deepest problems in this society would stem from the inherent contradictions within a system that is designed to exploit people without their knowledge. The most profound issues would include widespread psychological distress, the erosion of genuine social bonds, environmental collapse, intellectual stagnation, and systemic injustice. These issues would create a society that is fragile, unsustainable, and ultimately bound to collapse or evolve into something radically different. The greatest tragedy is that most people, within this system, would not even recognize their own subjugation—perpetuating a cycle of self-deception and resignation.</p>

<p><br /></p>

<h2 id="prompt-2">Prompt:</h2>

<p>How would an individual go about fixing those very deep problems?</p>

<h2 id="chatgpt-said-2">ChatGPT said:</h2>

<p>Fixing the deep, systemic problems in a society where the majority of people are enslaved without realizing it would be an incredibly difficult, complex, and long-term process. However, there are strategic steps that an individual or a small group of individuals could take to begin addressing these issues. The approach would require a combination of personal transformation, collective action, and strategic disruption of the system. Here’s a breakdown of how an individual might go about fixing these deep problems:</p>

<h3 id="1-self-awareness-and-personal-transformation">1. <strong>Self-Awareness and Personal Transformation</strong></h3>

<p><strong>Strategy</strong>: The first step to fixing societal problems is changing oneself. This involves awakening to the reality of one’s own situation and recognizing how deeply the system affects both individual lives and collective society.</p>

<ul>
  <li><strong>Critical Reflection</strong>: Begin by questioning everything—your values, the status quo, and the systems that govern your life. Recognize the ways in which you are complicit in, or trapped by, the system. Engage in deep self-reflection, journaling, and self-education to understand how you’ve been conditioned.</li>
  <li><strong>Unplug from the System</strong>: Gradually begin to detach from the systems that perpetuate your subjugation, such as consumerism, social media, or other distractions. This might involve reducing your screen time, questioning your spending habits, and engaging more in real-world, meaningful activities.</li>
  <li><strong>Develop Critical Thinking</strong>: Study philosophy, psychology, history, and political theory to gain a deeper understanding of how societies have been controlled in the past and how to organize for resistance. This helps in forming a vision of a better world.</li>
</ul>

<h3 id="2-building-community-and-solidarity">2. <strong>Building Community and Solidarity</strong></h3>

<p><strong>Strategy</strong>: Change on a societal scale requires collective action. The power of a single person is limited, but by connecting with others, you can begin to build a community of like-minded individuals who are committed to fighting the system.</p>

<ul>
  <li><strong>Find Like-Minded People</strong>: Seek out others who are questioning the system or who are already engaged in activism or social change. This could be through grassroots movements, political groups, or online communities focused on radical change.</li>
  <li><strong>Create Safe Spaces for Dialogue</strong>: Organize informal gatherings where people can discuss the problems in society without fear of censorship or retaliation. These spaces can serve as incubators for new ideas and strategies.</li>
  <li><strong>Empathy and Collective Action</strong>: Build relationships based on mutual respect and empathy. Encourage others to challenge their own beliefs and realize how the system exploits them. Use these connections to form collective actions, such as protests, campaigns, or mutual aid projects.</li>
</ul>

<h3 id="3-disrupting-the-economic-system">3. <strong>Disrupting the Economic System</strong></h3>

<p><strong>Strategy</strong>: Economic control is at the heart of most forms of modern slavery. To fix this, individuals must work toward creating alternatives to the current economic system that empowers people rather than exploits them.</p>

<ul>
  <li><strong>Financial Independence</strong>: One way to escape the cycle of debt and economic dependency is to work toward financial independence. This could involve reducing reliance on exploitative industries, starting alternative forms of income (e.g., cooperative businesses, freelancing), or even adopting a minimalist lifestyle to reduce consumer needs.</li>
  <li><strong>Support Worker Cooperatives</strong>: Invest your time, energy, or money into businesses that are worker-owned and democratically run. These cooperative businesses don’t just aim to profit the owners but distribute wealth more fairly among workers.</li>
  <li><strong>Advocate for Universal Basic Income (UBI)</strong>: Support or start campaigns for policies like UBI, which would provide a living wage to every citizen, reducing the dependency on exploitative labor and allowing people more freedom to engage in creative, meaningful work.</li>
</ul>

<h3 id="4-challenging-the-information-and-media-system">4. <strong>Challenging the Information and Media System</strong></h3>

<p><strong>Strategy</strong>: The media plays a crucial role in keeping people distracted and uninformed. To fix this, individuals need to become active consumers and creators of information, and disrupt the dominant narratives pushed by the ruling class.</p>

<ul>
  <li><strong>Engage in Independent Media</strong>: Seek out independent, alternative sources of news and information. Support independent journalists and media outlets that challenge the mainstream narratives controlled by corporate or governmental powers.</li>
  <li><strong>Create and Share Knowledge</strong>: Start blogging, podcasting, or making videos that provide critical perspectives on the system. Share knowledge on how people can break free from consumerism, debt, and political manipulation. This is part of building a counter-narrative.</li>
  <li><strong>Disrupt Social Media</strong>: Use social media platforms to spread awareness and organize, but be strategic. Social media can be a tool for activism, but it must be used to build real-world action and not just to engage in superficial debates.</li>
</ul>

<h3 id="5-promote-education-for-liberation">5. <strong>Promote Education for Liberation</strong></h3>

<p><strong>Strategy</strong>: Education is one of the most powerful tools for dismantling the oppressive systems that perpetuate slavery. Changing the educational system or creating alternative learning environments is essential.</p>

<ul>
  <li><strong>Teach Critical Thinking</strong>: If you’re in a position to educate others (whether as a parent, teacher, or mentor), prioritize critical thinking over rote memorization. Encourage students to question authority, analyze historical and contemporary power structures, and think creatively about solutions.</li>
  <li><strong>Build Alternative Learning Systems</strong>: Support or create educational initiatives outside of traditional institutions, such as community schools, online education platforms, or mentorship programs that teach people how to challenge the status quo and develop practical skills for self-sufficiency.</li>
  <li><strong>Promote Collective Knowledge</strong>: Encourage the sharing of knowledge between communities to empower people. This might include community-led education on issues such as economic justice, climate change, and political power. Knowledge should be decentralized and accessible to all.</li>
</ul>

<h3 id="6-engage-in-direct-action-and-political-activism">6. <strong>Engage in Direct Action and Political Activism</strong></h3>

<p><strong>Strategy</strong>: To create change, individuals must actively challenge the system in ways that disrupt its operations and demand reforms or revolution.</p>

<ul>
  <li><strong>Protest and Civil Disobedience</strong>: Join or organize peaceful protests, demonstrations, and acts of civil disobedience that draw attention to the injustices in the system. Use these actions to put pressure on policymakers and corporations to enact change.</li>
  <li><strong>Engage in Political Campaigns</strong>: Support or run for political office with the goal of enacting systemic change. Advocate for policies that reduce inequality, such as universal healthcare, free education, wealth redistribution, and corporate regulation.</li>
  <li><strong>Defend Freedom of Speech and Assembly</strong>: Advocate for the protection of democratic rights like freedom of speech and the right to protest. Fight against censorship, surveillance, and repression of activists.</li>
</ul>

<h3 id="7-reconstructing-social-systems-and-values">7. <strong>Reconstructing Social Systems and Values</strong></h3>

<p><strong>Strategy</strong>: To create a truly free society, the very values that underpin the existing system must be changed. This involves redefining success, community, and the meaning of freedom.</p>

<ul>
  <li><strong>Redefine Success</strong>: Challenge the notion that success is about wealth accumulation and individual achievement. Promote the idea that true success is about collective well-being, happiness, and self-actualization. This would involve shifting societal values away from competition toward cooperation, mutual aid, and social justice.</li>
  <li><strong>Foster Compassion and Empathy</strong>: Build a culture of compassion and empathy where people recognize their interconnectedness. This would involve teaching people to care for one another and the environment, creating a society that values mutual support over individual gain.</li>
  <li><strong>Decentralize Power</strong>: Support initiatives that decentralize power, whether that’s through local community organizing, cooperative governance, or democratic decision-making processes. The idea is to prevent any one group from holding too much control over the rest of society.</li>
</ul>

<h3 id="8-build-a-movement-for-long-term-change">8. <strong>Build a Movement for Long-Term Change</strong></h3>

<p><strong>Strategy</strong>: Change doesn’t happen overnight. It requires building momentum and creating an enduring movement that can outlast setbacks and resistance.</p>

<ul>
  <li><strong>Start Small, Think Big</strong>: Begin with local actions and projects, but always keep in mind the larger goal of societal transformation. Mobilize community leaders, activists, and thinkers to join the cause and amplify the impact.</li>
  <li><strong>Foster Alliances</strong>: Build coalitions across different groups and movements—environmental, racial justice, labor rights, and political reform. The more diverse and united the movement, the stronger it will be in challenging the system.</li>
  <li><strong>Create Resilient Networks</strong>: Build long-term, sustainable support structures, such as mutual aid networks, alternative media outlets, and political organizations, that can survive even in the face of state repression or social apathy.</li>
</ul>

<h3 id="conclusion-2">Conclusion</h3>

<p>To address the deep problems in this hypothetical society, an individual must start by breaking free from the system’s grip on their own mind and lifestyle. From there, they can begin to connect with others, disrupt the economic and political systems, challenge the media narratives, and advocate for a new model of education and social organization. It’s a journey of personal awakening and collective action, where the goal is not only to liberate oneself but to help create a world where true freedom, justice, and equality can thrive. While the challenge is immense, history has shown that even the most entrenched systems of control can be dismantled through sustained and strategic resistance.</p>
]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[How to Disable a Link]]></title>
    <link href="https://simonewebdesign.it/how-to-disable-a-link/"/>
    <updated>2024-04-04T00:00:00+00:00</updated>
    <id>https://simonewebdesign.it/how-to-disable-a-link</id>
    <content type="html"><![CDATA[<p>The HTML language is pretty awesome. It’s constantly evolving, just like CSS and JavaScript, and likely has anything you need out of the box.</p>

<p>This time I’ll cover a lesser-known HTML attribute, <code class="language-plaintext highlighter-rouge">inert</code>. It’s kind of like <code class="language-plaintext highlighter-rouge">disabled</code>, but not quite.</p>

<p>If you need to <strong>disable a link</strong>, you might be tempted to do it this way:</p>

<div class="language-html highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="nt">&lt;a</span> <span class="na">href=</span><span class="s">"#"</span> <span class="na">disabled</span><span class="nt">&gt;</span>I am a disabled link<span class="nt">&lt;/a&gt;</span>
</code></pre></div></div>

<p>Or maybe through CSS:</p>

<div class="language-css highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="nt">a</span><span class="o">[</span><span class="nt">disabled</span><span class="o">]</span> <span class="p">{</span>
  <span class="nl">pointer-events</span><span class="p">:</span> <span class="nb">none</span><span class="p">;</span>
<span class="p">}</span>
</code></pre></div></div>

<p>These are <strong>both wrong</strong>.</p>

<p>Links <em>do not</em> have a <code class="language-plaintext highlighter-rouge">disabled</code> attribute, so it just won’t work.</p>

<p><code class="language-plaintext highlighter-rouge">pointer-events: none</code> kind of works, if you happen to be using a <em>pointer</em> (a pointer is the mouse cursor, or if you’re on mobile, it’s where your finger is touching). It <em>will</em> disable the link, however <strong>it won’t work for keyboard users</strong>.</p>

<p>Since it’s important to <strong>keep all kinds of users and interfaces in consideration</strong> (in other words, <strong>accessibility matters</strong>), the <code class="language-plaintext highlighter-rouge">inert</code> property was born.</p>

<blockquote>
  <p><strong>inert</strong> is a boolean value that, when present, makes the browser "ignore" user input events for the element, including focus events and events from assistive technologies.</p>
  <footer>
    <cite>
      — <a href="https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/inert" rel="external noopener noreferrer nofollow">HTMLElement: inert property on MDN</a>
    </cite>
  </footer>
</blockquote>

<p>Why is this important? Because simply hiding a link, or even moving it offscreen, <strong>doesn’t automatically make it inaccessible to all users</strong>. A screen reader user, for example, would still be able to access it.</p>

<h2 id="working-example">Working example</h2>

<p>This is the modern, “right” way:</p>

<div class="language-html highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="nt">&lt;a</span> <span class="na">href=</span><span class="s">"http://example.com"</span> <span class="na">inert</span><span class="nt">&gt;</span>I am an inert link<span class="nt">&lt;/a&gt;</span>
</code></pre></div></div>

<p>Pretty simple, isn’t it? Try it here below:</p>

<p><a href="http://example.com" inert="">I am an inert link</a></p>

<h2 id="styling-with-css">Styling with CSS</h2>

<p>The <code class="language-plaintext highlighter-rouge">inert</code> attribute <strong>comes with no CSS by default</strong>, but of course you’re free to style it in any way you like. For example, to make all the disabled links slightly transparent, you could do this:</p>

<div class="language-css highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="nt">a</span><span class="o">[</span><span class="nt">inert</span><span class="o">]</span> <span class="p">{</span>
  <span class="nl">opacity</span><span class="p">:</span> <span class="m">.5</span><span class="p">;</span>
<span class="p">}</span>
</code></pre></div></div>

<h2 id="browser-compatibility">Browser compatibility</h2>

<p>The attribute is widely supported in all major web browsers, since Chrome 102 (released in April 2022).
You can find more information on the <a href="https://developer.mozilla.org/en-US/docs/Web/HTML/Global_attributes/inert">inert</a> page on mdn.</p>

<hr />

<p>That’s it! I hope you’ve enjoyed reading and found the solution you were looking for. Happy hacking!</p>
]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[How to Link to Headings in Markdown]]></title>
    <link href="https://simonewebdesign.it/anchor-link-heading-markdown/"/>
    <updated>2023-03-27T00:00:00+00:00</updated>
    <id>https://simonewebdesign.it/anchor-link-heading-markdown</id>
    <content type="html"><![CDATA[<p>I use <a href="https://jekyllrb.com/">Jekyll</a> and I wanted to make all of my headings linkable.</p>

<p>In HTML you can achieve this with a simple <a href="https://developer.mozilla.org/en-US/docs/Web/HTML/Element/a#linking_to_an_element_on_the_same_page">link to an element on the same page</a>, except that the link would be self-referencing — for example:</p>

<div class="language-html highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="nt">&lt;h2</span> <span class="na">id=</span><span class="s">"my-heading"</span><span class="nt">&gt;</span>
  <span class="nt">&lt;a</span> <span class="na">href=</span><span class="s">"#my-heading"</span><span class="nt">&gt;</span>My Heading<span class="nt">&lt;/a&gt;</span>
<span class="nt">&lt;/h2&gt;</span>
</code></pre></div></div>

<p>In Markdown, it is equivalent to:</p>

<div class="language-md highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="gu">## [My Heading](#my-heading)</span>
</code></pre></div></div>

<!--more-->

<p>This works because <a href="https://jekyllrb.com/docs/configuration/markdown/#kramdown">Kramdown</a>, the default Markdown renderer for Jekyll, automatically adds <code class="language-plaintext highlighter-rouge">id</code> attributes, using a <em>slugified</em> version of your heading text. So, for example:</p>

<div class="language-md highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="gu">### Some text</span>
</code></pre></div></div>

<p>Conveniently gets rendered as:</p>

<div class="language-html highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="nt">&lt;h3</span> <span class="na">id=</span><span class="s">"some-text"</span><span class="nt">&gt;</span>Some text<span class="nt">&lt;/h3&gt;</span>
</code></pre></div></div>

<h2 id="appending-a-symbol-to-the-heading"><a href="#appending-a-symbol-to-the-heading">Appending a symbol to the heading</a></h2>

<p>Often times I’ve seen a <code class="language-plaintext highlighter-rouge">#</code> symbol, or maybe a link symbol (🔗) either at the beginning or at the end of the heading.</p>

<p>Consider this example I found on the web:</p>

<div class="language-html highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="nt">&lt;h3</span> <span class="na">id=</span><span class="s">"example-1"</span><span class="nt">&gt;</span>
  Example
  <span class="nt">&lt;a</span> <span class="na">aria-hidden=</span><span class="s">"true"</span> <span class="na">href=</span><span class="s">"#example-1"</span> <span class="na">hidden</span><span class="nt">&gt;</span>#<span class="nt">&lt;/a&gt;</span>
<span class="nt">&lt;/h3&gt;</span>
</code></pre></div></div>

<p>I think hiding the symbol to assistive tech makes a lot of sense — it is more of a presentational thing, after all. However, decorative things like this don’t have to belong to the HTML — they can be defined in CSS, like:</p>

<div class="language-css highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="nt">h2</span><span class="nd">::after</span><span class="o">,</span>
<span class="nt">h3</span><span class="nd">::after</span> <span class="p">{</span>
  <span class="nl">content</span><span class="p">:</span> <span class="s2">' #'</span><span class="p">;</span>
<span class="p">}</span>
</code></pre></div></div>

<p>Even better, you can make it appear only on hover, or when there is a link. Ultimately I settled with this for my blog:</p>

<div class="language-css highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="nt">h2</span><span class="nd">:hover</span> <span class="o">&gt;</span> <span class="nt">a</span><span class="nd">::after</span><span class="o">,</span>
<span class="nt">h3</span><span class="nd">:hover</span> <span class="o">&gt;</span> <span class="nt">a</span><span class="nd">::after</span> <span class="p">{</span>
    <span class="nl">content</span><span class="p">:</span> <span class="s2">' #'</span><span class="p">;</span>
<span class="p">}</span>
</code></pre></div></div>

<h2 id="should-the-entire-heading-be-a-link-or-just-the-symbol"><a href="#should-the-entire-heading-be-a-link-or-just-the-symbol">Should the entire heading be a link, or just the symbol?</a></h2>

<p>I’m unsure what’s best practice here, but it just seems very convenient to be able to link to any section of a document in general. Ultimately I don’t think it matters too much, but MDN makes the whole heading a link, and again, the symbol at the end of it is just presentational and should ideally be hidden for accessibility.</p>

<h2 id="a-future-optimization"><a href="#a-future-optimization">A future optimization</a></h2>

<p>It would be cool to be able to keep writing regular headings - i.e. if <code class="language-plaintext highlighter-rouge">## My Heading</code> would automatically turn into a link. I think this could be done by configuring Kramdown, or maybe via a plugin. If you find a way to enable this, please let me know in the comments below!</p>
]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[One request]]></title>
    <link href="https://simonewebdesign.it/1req/"/>
    <updated>2022-10-09T00:00:00+00:00</updated>
    <id>https://simonewebdesign.it/one-request</id>
    <content type="html"><![CDATA[<blockquote>
  <p>In an era where 95% of sites are bloated with cookie banners and behavioral tracking scripts, here’s a refreshing approach to web development.</p>
</blockquote>

<p>Nowadays, loading a website on your device of choice can be painful — both for the browser, which has to parse and render all that stuff, and for you, the user, who has to wait for it (and pay for that data plan).</p>

<p>The issue is only exacerbated by the fact that mobile devices can be slow, the network can be slow, and there’s simply too much <a href="https://en.wikipedia.org/wiki/Cruft">cruft</a> to download.</p>

<p>There is a better way.<!--more--></p>

<p><strong>What if you could make your entire website fit into a single page?</strong></p>

<p>A lot of sites are built as a single page (can we have more of those?)— and no, I don’t mean a <a href="https://en.wikipedia.org/wiki/Single-page_application">SPA</a>. I’m talking about something radically different here. Essentially, the challenge boils down to this:</p>

<p><strong>Can I reduce every page down to a single HTTP request?</strong></p>

<p>First of all, <em>why?</em> You may ask. Well, many reasons. I did this to my blog, <a href="https://simonewebdesign.it">simonewebdesign.it</a>. I mostly did it just to prove it possible, but it turned out to be a fun challenge that kept me busy for months and resulted in a much faster, more maintainable website, with a <a href="https://www.websitecarbon.com/website/simonewebdesign-it/">very small carbon footprint</a>.</p>

<!-- <abbr title="too long; didn't read">TL;DR</abbr>: Our planet matters. User experience matters. Speed matters. -->

<p>But the real question is, <em>how</em>?</p>

<h2 id="inlining-all-the-things"><a href="#inlining-all-the-things">Inlining <em>all the things</em></a></h2>

<p>This is essentially how I’ve done it. I’ve <a href="https://gomakethings.com/inlining-literally-everything-for-better-performance/">inlined everything</a> that could’ve possibly been inlined. Keep reading if you’re curious and want to know how I achieved this.</p>

<h3 id="inline-styles">Inline styles</h3>

<p>This is where the journey started. I refactored some CSS, got rid of a few superfluous HTML tags, and the stylesheet got so small that I thought, why not just inline it? So I looked into that.</p>

<p>I thought I should be able to <em>inline</em> the compiled <code class="language-plaintext highlighter-rouge">style.css</code>’s contents into a <code class="language-plaintext highlighter-rouge">&lt;style&gt;</code> tag, somehow. This turned out to be a challenge. I couldn’t find a tool that did exactly this, so I wrote my own — or, to be more specific, I sent a pull request to <a href="https://github.com/mahhov/inline-scripts">inline-scripts</a>, which seemed like the closest thing I could find. At first, all it was doing was inlining <code class="language-plaintext highlighter-rouge">&lt;script&gt;</code> tags, so I only had to do the same, but for CSS — a simpler job, figuratively speaking.</p>

<p>Anyway, with some clever Ruby scripting I managed to minify all the HTML, CSS and JS in one go. I would first inline the CSS “on the spot” (i.e. without creating a new file):</p>

<div class="language-rb highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="no">Dir</span><span class="p">[</span><span class="s2">"public/**/*.html"</span><span class="p">].</span><span class="nf">each</span> <span class="k">do</span> <span class="o">|</span><span class="n">file</span><span class="o">|</span>
  <span class="nb">puts</span> <span class="s2">"Processing </span><span class="si">#{</span><span class="n">file</span><span class="si">}</span><span class="s2">..."</span>
  <span class="nb">system</span> <span class="s2">"node_modules/.bin/inline-stylesheets </span><span class="si">#{</span><span class="n">file</span><span class="si">}</span><span class="s2"> </span><span class="si">#{</span><span class="n">file</span><span class="si">}</span><span class="s2">"</span>
<span class="k">end</span>
</code></pre></div></div>

<p>I would then run <a href="https://github.com/kangax/html-minifier">html-minifier</a> as such:</p>

<div class="language-sh highlighter-rouge"><div class="highlight"><pre class="highlight"><code>html-minifier <span class="nt">--file-ext</span> html <span class="nt">--case-sensitive</span> <span class="se">\</span>
 <span class="nt">--collapse-boolean-attributes</span> <span class="nt">--collapse-whitespace</span> <span class="se">\</span>
 <span class="nt">--minify-css</span> <span class="nb">true</span> <span class="nt">--minify-js</span> <span class="nb">true</span> <span class="se">\</span>
 <span class="nt">--remove-attribute-quotes</span> <span class="nt">--remove-comments</span> <span class="se">\</span>
 <span class="nt">--remove-empty-attributes</span> <span class="nt">--remove-empty-elements</span> <span class="se">\</span>
 <span class="nt">--remove-optional-tags</span> <span class="nt">--remove-redundant-attributes</span> <span class="se">\</span>
 <span class="nt">--remove-script-type-attributes</span> <span class="se">\</span>
 <span class="nt">--remove-style-link-type-attributes</span> <span class="se">\</span>
 <span class="nt">--remove-tag-whitespace</span> <span class="nt">--sort-attributes</span> <span class="se">\</span>
 <span class="nt">--sort-class-name</span> <span class="nt">--trim-custom-fragments</span> <span class="se">\</span>
 <span class="nt">--use-short-doctype</span>
</code></pre></div></div>

<p>And there you have it — a highly optimized, one-liner HTML file with inline CSS and JS — for every page.</p>

<h3 id="inline-manifestjson">Inline manifest.json</h3>

<p>The <a href="https://developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json">manifest.json</a> is usually pretty small, so it makes sense to inline it.</p>

<p>How did I do this? It was actually pretty simple: I made it into a data URI of type <code class="language-plaintext highlighter-rouge">data:application/manifest+json</code>, which is then loaded as a <code class="language-plaintext highlighter-rouge">&lt;link rel="manifest"&gt;</code>, just as usual. Here it is, in its full one-line glory:</p>

<div class="language-html highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="nt">&lt;link</span> <span class="na">href=</span><span class="s">'data:application/manifest+json,{"name":"Simone Web Design","short_name":"SimoneDesign","theme_color":"%23555","background_color":"%23f6f6f6","display":"minimal-ui","description":"A tech blog"}'</span> <span class="na">rel=</span><span class="s">manifest</span><span class="nt">&gt;</span>
</code></pre></div></div>

<p>The only catch was that I had to <a href="https://stackoverflow.com/a/67244614/801544">encodeURIComponent</a>.</p>

<h2 id="analytics"><a href="#analytics">Analytics</a></h2>

<p>I got rid of client-side analytics. <a href="https://www.cloudflare.com/">Cloudflare</a> already gives me enough stats, such as the number of requests, unique visits and page views, grouped by visiting country. I don’t really need any more than that.</p>

<p>As an interesting side note, when I check the analytics on Cloudflare, it also shows a Carbon Impact Report, which claims to have saved me 836 grams of carbon (in 2020 vs average data centers) — this is equivalent to turning off one lightbulb for 20 hours, apparently. It sounds an awful lot like <a href="https://en.wikipedia.org/wiki/Greenwashing">greenwashing</a>, if you ask me, but to be fair they do seem to have put effort on reducing the <a href="https://blog.cloudflare.com/helping-build-a-green-internet/">Internet’s environmental impact</a>.</p>

<h2 id="the-server"><a href="#the-server">The server</a></h2>

<p>I use <a href="https://puma.io/">Puma</a>. It is a fast server that provides <a href="https://en.wikipedia.org/wiki/Parallel_computing">parallelism</a> out of the box. This is what my <a href="https://devcenter.heroku.com/articles/procfile">Procfile</a> looks like:</p>

<div class="language-sh highlighter-rouge"><div class="highlight"><pre class="highlight"><code>web: bundle <span class="nb">exec </span>puma <span class="nt">--threads</span> 8:32 <span class="nt">--workers</span> 3 <span class="nt">-p</span> <span class="nv">$PORT</span>
</code></pre></div></div>

<p>Basically what this means is that, at any given time, there are 8 threads ready to serve you a request, over 3 separate clusters.</p>

<p>This may be a little overkill, since I also use Cloudflare as a caching layer on top of this server, which is load balanced and globally distributed. I also don’t usually get much traffic, so this definitely achieves the goal of speed.</p>

<h2 id="hosting-and-dns"><a href="#hosting-and-dns">Hosting and DNS</a></h2>

<p>I recently switched to a new hosting provider, <a href="https://fly.io/">Fly.io</a>. I had to do that since Heroku, my old provider, unfortunately <a href="https://blog.heroku.com/next-chapter">discontinued their free plan</a>. Sad news, I’ve used it for 10 years, but it was time to move on.</p>

<p>Fly has a pretty sound infrastructure with modern features:</p>

<ul>
  <li>Edge TLS termination. By handling TLS <em>at the edge</em>, the handshake is handled by the nearest datacenter to the user. As a result, <strong>latency is decreased</strong>.</li>
  <li>High performance micro VMs on bare metal servers. <strong>The server replies faster</strong>.</li>
  <li>HTTP2 and Brotli compression. <strong>The data gets sent faster</strong>.</li>
</ul>

<p>Last but not the least, I was able to remove a <a href="https://en.wikipedia.org/wiki/CNAME_record">CNAME record</a> and use an <a href="https://en.wikipedia.org/wiki/List_of_DNS_record_types#A">A record</a> instead. This resulted in <strong>one less server roundtrip</strong>.</p>

<h2 id="other-minor-optimizations"><a href="#other-minor-optimizations">Other minor optimizations</a></h2>

<p>These are loosely related to the “one request” thing, but still worth mentioning.</p>

<h3 id="moving-to-modern-media-formats">Moving to modern media formats</h3>

<p>Lots of formats have actually been superseded by more efficient ones: <abbr title="Portable Network Graphics">PNG</abbr> to WebP, <abbr title="Graphics Interchange Format">GIF</abbr> to MP4, <abbr title="Joint Photographic Experts Group">JPEG</abbr> to <abbr title="AV1 Image File Format">AVIF</abbr>… <a href="https://developer.mozilla.org/en-US/docs/Web/Media/Formats/Image_types">the list goes on</a> — these are just the ones I’m aware of. I don’t think these should be inlined, but new formats are definitely worth the effort, since they’re much more performant.</p>

<h3 id="the-favicon">The favicon</h3>

<p>I went from <abbr title="Portable Network Graphics">PNG</abbr> to <abbr title="Scalable Vector Graphics">SVG</abbr> for the favicon, which I blatantly stole from Peter Selinger, the guy behind <a href="https://potrace.sourceforge.net/">Potrace</a> <small>(it was public domain, technically)</small>. What I did on my part was optimizing it even further, using Jake Archibald’s wonderful <a href="https://jakearchibald.github.io/svgomg/">SVGOMG</a>, powered by <a href="https://github.com/svg/svgo">SVGO</a>.</p>

<p>As for inlining it, I had to serialize it into a data URI using <a href="https://github.com/tigt/mini-svg-data-uri">mini-svg-data-uri</a>. I even ended up making a <abbr title="Command-line interface">CLI</abbr> out of it — it’s something I had to do anyway, and <a href="https://github.com/tigt/mini-svg-data-uri/pull/19">contributing back</a> was the least I could have done.</p>

<h3 id="the-fonts">The fonts</h3>

<p>I got rid of the custom Google font I was using and went for system fonts. This is what I have now:</p>

<div class="language-css highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="nt">html</span> <span class="p">{</span>
  <span class="nl">font-family</span><span class="p">:</span> <span class="s1">"PT Serif"</span><span class="p">,</span> <span class="n">Georgia</span><span class="p">,</span> <span class="n">Times</span><span class="p">,</span> <span class="s1">"Times New Roman"</span><span class="p">,</span> <span class="nb">serif</span><span class="p">;</span>
<span class="p">}</span>
</code></pre></div></div>

<p>I don’t actually provide PT Serif, however. If your machine happens to have that, great — if not, it’ll fall back to the next one. I might reconsider this choice in the future, but for now, this is good enough.</p>

<h3 id="the-javascript">The JavaScript</h3>

<p>I waited until the end to say this, because you probably wouldn’t have believed me, but <strong>this site doesn’t have any JavaScript</strong>, the only exception being made for the <a href="https://developer.mozilla.org/en-US/docs/Web/API/Service_Worker_API">ServiceWorker</a> registration:</p>

<div class="language-js highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="o">&lt;</span><span class="nx">script</span><span class="o">&gt;</span>
  <span class="nb">navigator</span><span class="p">.</span><span class="nx">serviceWorker</span><span class="p">.</span><span class="nf">register</span><span class="p">(</span><span class="dl">"</span><span class="s2">/sw.js</span><span class="dl">"</span><span class="p">)</span>
<span class="o">&lt;</span><span class="sr">/script</span><span class="err">&gt;
</span></code></pre></div></div>

<p><a href="https://simonewebdesign.it/sw.js">The ServiceWorker</a> is actually a separate JS file, because I couldn’t find a way to inline that (if you do know of a way, please let me know). But, other than that (and Disqus, which I’m planning to remove soon), I don’t need JS at all. <span role="img" aria-label="shrugs">¯\_(ツ)_/¯</span></p>

<h2 id="conclusion"><a href="#conclusion">Conclusion</a></h2>

<p>I hope you liked this article at least as much as I enjoyed writing it. I hope it tickled your curiosity, to the very least, and that - by shedding a light on the importance of performance - I’ve inspired you to take action and improve your own site. <!-- Either way, it's been a fun ride. For the records, I started writing this on September 20<sup>th</sup>, 2021. Glad I got round to finishing it. --></p>
]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[How to Install Global npm Packages on Heroku]]></title>
    <link href="https://simonewebdesign.it/how-to-install-global-npm-packages-on-heroku/"/>
    <updated>2021-05-29T00:00:00+00:00</updated>
    <id>https://simonewebdesign.it/how-to-install-global-npm-packages-on-heroku</id>
    <content type="html"><![CDATA[<p>If you need to install an <a href="https://www.npmjs.com/">npm</a> package <em>globally</em>, rather than <em>locally</em>, but don’t know how to do this on <a href="https://www.heroku.com/">Heroku</a>, you can follow this how-to guide.</p>

<!--more-->

<p>Before we start, a quick word of warning: it’s generally considered good practice to install your npm dependencies in the local <code class="language-plaintext highlighter-rouge">node_modules</code> folder, whenever possible. This means simply running <code class="language-plaintext highlighter-rouge">npm install</code> without the <code class="language-plaintext highlighter-rouge">--global</code> (<code class="language-plaintext highlighter-rouge">-g</code>) flag. However, sometimes this is not an option, for instance if you have a library or tool that expects a binary to be already present in the system, like in my case.</p>

<h1 id="the-problem">The problem</h1>

<p>Essentially, I had one problem: <strong>a Ruby gem that needed a Node.js package</strong> to be installed <strong>globally</strong>.</p>

<p>I had a <a href="https://jekyllrb.com/">Jekyll</a> blog use <a href="https://pugjs.org/">Pug</a> (Jade) for templating. Making Pug work locally was very easy using <a href="https://github.com/DougBeney/jekyll-pug">Jekyll-Pug</a>, a Jekyll plugin that enables Pug templates. However, when deploying on <a href="https://www.heroku.com/">Heroku</a>, the build would fail because of the missing Pug library.</p>

<p>The <a href="https://github.com/DougBeney/jekyll-pug">Jekyll-Pug</a> README is pretty clear:</p>

<blockquote>
  <p><strong>Note:</strong> you must have pug installed. To install it, simply enter the terminal command, <code class="language-plaintext highlighter-rouge">npm install pug -g</code>.</p>
</blockquote>

<p>Two issues here:</p>

<ol>
  <li>I was using <a href="https://github.com/heroku/heroku-buildpack-ruby">Heroku’s Ruby Buildpack</a>, but I also needed Node.js to be able to run <code class="language-plaintext highlighter-rouge">npm</code>;</li>
  <li>I wasn’t sure how to declare the global Node.js dependency.</li>
</ol>

<h1 id="the-solution">The solution</h1>

<p>Point #1 was pretty straightforward: I simply needed to add the <a href="https://elements.heroku.com/buildpacks/heroku/heroku-buildpack-nodejs">Heroku Buildpack for Node.js</a> alongside the Ruby one, essentially <a href="https://devcenter.heroku.com/articles/using-multiple-buildpacks-for-an-app">using two buildpacks instead of one</a>. You can do this by running:</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>heroku buildpacks:add --index 1 heroku/nodejs
</code></pre></div></div>

<p>This will insert the Node.js buildpack <em>before</em> Ruby, so it will be executed first.</p>

<p>Point #2 was about installing Pug globally. The way I went to achieve this was by using package.json’s <a href="https://docs.npmjs.com/cli/v7/using-npm/scripts">scripts</a>. This is what my package.json looked like:</p>

<div class="language-json highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="p">{</span><span class="w">
  </span><span class="nl">"scripts"</span><span class="p">:</span><span class="w"> </span><span class="p">{</span><span class="w">
    </span><span class="nl">"build"</span><span class="p">:</span><span class="w"> </span><span class="s2">"npm install pug --global"</span><span class="w">
  </span><span class="p">}</span><span class="w">
</span><span class="p">}</span><span class="w">
</span></code></pre></div></div>

<p>The <code class="language-plaintext highlighter-rouge">npm install pug --global</code> command would run on Heroku when pushing and, thanks to the <a href="https://devcenter.heroku.com/articles/nodejs-support#multi-buildpack-behavior">multi-buildpack behaviour</a>, all Node.js-related binaries would be available in subsequent buildpacks as well.</p>

<p>So in my specific case, this meant that Jekyll could find the global Pug binary and compile the blog successfully. Problem solved!</p>

<h1 id="conclusion">Conclusion</h1>

<p>Whilst global dependencies are to avoid whenever possible, Heroku lets us run arbitrary commands and generate any build artifacts needed for our apps to function correctly. <a href="https://devcenter.heroku.com/articles/buildpacks">Buildpacks</a> are Heroku’s way of handling dependencies and compile code. They have a <a href="https://devcenter.heroku.com/articles/buildpacks#officially-supported-buildpacks">list of official buildpacks</a> for us to use, for free — and if you ever need to install a global dependency (or run any arbitrary command in Node.js, for that matter), you can do so using <a href="https://docs.npmjs.com/cli/v7/using-npm/scripts">scripts</a> in your package.json.</p>

]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[Multiple Git Config For Different Folders]]></title>
    <link href="https://simonewebdesign.it/multiple-git-config-for-different-folders/"/>
    <updated>2020-11-23T00:00:00+00:00</updated>
    <id>https://simonewebdesign.it/multiple-git-config-for-different-folders</id>
    <content type="html"><![CDATA[<p>I wanted to have a clean separation between work-related repositories and my personal projects, as I often need to use a different email: for example, I’d like to sign git commits in the work repo with my work email, but keep using my personal email for the rest. How do you achieve this?</p>

<p>It’s actually pretty simple: I’ll show you how.</p>

<!--more-->

<h2 id="two-folders--one-for-your-projects-one-for-work">Two folders — one for your projects, one for work</h2>

<p>I like the idea of having two folders, each containing <em>many</em> git repositories: I’ll call them <code class="language-plaintext highlighter-rouge">Work</code> and <code class="language-plaintext highlighter-rouge">Projects</code>, but you’re naturally free to name them the way you prefer.</p>

<p>The first step is to <strong>create a file</strong> in your home directory, named <code class="language-plaintext highlighter-rouge">.gitconfig</code>. You probably have it already, and that’s fine. Just <strong>open it and paste this</strong>:</p>

<div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="p">[</span><span class="n">includeIf</span> <span class="sh">"</span><span class="s">gitdir:~/Work/</span><span class="sh">"</span><span class="p">]</span>
  <span class="n">path</span> <span class="o">=</span> <span class="o">~/</span><span class="n">Work</span><span class="o">/</span><span class="p">.</span><span class="n">gitconfig</span>
<span class="p">[</span><span class="n">includeIf</span> <span class="sh">"</span><span class="s">gitdir:~/Projects/</span><span class="sh">"</span><span class="p">]</span>
  <span class="n">path</span> <span class="o">=</span> <span class="o">~/</span><span class="n">Projects</span><span class="o">/</span><span class="p">.</span><span class="n">gitconfig</span>
</code></pre></div></div>

<p>It’s pretty self-explanatory, right? We’re essentially saying:</p>

<ul>
  <li>If the dir matches <code class="language-plaintext highlighter-rouge">~/Work/</code>, include the config located at path <code class="language-plaintext highlighter-rouge">~/Work/.gitconfig</code>;</li>
  <li>If the dir matches <code class="language-plaintext highlighter-rouge">~/Projects/</code>, include the config located at path <code class="language-plaintext highlighter-rouge">~/Projects/.gitconfig</code> .</li>
</ul>

<p>Note you don’t even need to create these files — just use <code class="language-plaintext highlighter-rouge">git config</code> to write in them. For example, to use your work email on all work-related repos, you might do:</p>

<div class="language-bash highlighter-rouge"><div class="highlight"><pre class="highlight"><code>git config <span class="nt">--file</span> ~/Work/.gitconfig user.email john@example.work
</code></pre></div></div>

<p>This is great, because we can now have <strong>completely separate configurations</strong>, each living in their own separate folder, and the right configuration will be applied depending on the location. Awesome!</p>

<h3 id="caveats">Caveats</h3>

<p>There are a few little caveats to be aware of, just in case you run into issues. If you do, you may want to read the <em>Includes</em> section in the <a href="https://git-scm.com/docs/git-config#_includes">official docs</a> — for example, you know the trailing slash in <code class="language-plaintext highlighter-rouge">gitdir:~/Work/</code>? You’d think it wouldn’t matter, but it does: if the path ends with <code class="language-plaintext highlighter-rouge">/</code>, it matches <code class="language-plaintext highlighter-rouge">Work</code> and <strong>everything inside, recursively</strong>. Also, don’t add a space between <code class="language-plaintext highlighter-rouge">gitdir:</code> and the path, or it won’t work.</p>

<h3 id="sharing-common-configuration">Sharing common configuration</h3>

<p>You’ll likely want to avoid repeating yourself and share the common bits of configuration, such as <a href="https://www.git-scm.com/book/en/v2/Git-Basics-Git-Aliases">git aliases</a>, if you have any.</p>

<p>If that’s the case, just keep those in the global config. You can do so by using the <code class="language-plaintext highlighter-rouge">--global</code> flag, for example:</p>

<div class="language-bash highlighter-rouge"><div class="highlight"><pre class="highlight"><code>git config <span class="nt">--global</span> alias.st status
</code></pre></div></div>

<hr />

<p>I hope you found this useful. If you run into trouble, feel free to leave me a comment below and I’ll try to help. <a href="https://hades.github.io/2010/01/git-your-friend-not-foe">Remember, git is your friend</a>.</p>
]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[Inserting values of multiple types in Rust's HashMap]]></title>
    <link href="https://simonewebdesign.it/rust-hashmap-insert-values-multiple-types/"/>
    <updated>2020-07-06T00:00:00+00:00</updated>
    <id>https://simonewebdesign.it/rust-hashmap-insert-values-multiple-types</id>
    <content type="html"><![CDATA[<p>I was building a generic data store with Rust and I needed to implement a <strong>heterogeneous collection</strong> of keys and values. Essentially what I needed was a dictionary, but with values of dynamic type, like both strings and integers at the same time.</p>

<p>Rust is a statically typed language and, due to the memory safety guarantees we are given, all values of some type must have a known, fixed size at compile time, therefore we are not allowed to create a collection of multiple types. However, <a href="https://doc.rust-lang.org/reference/dynamically-sized-types.html" rel="external">dynamically sized types</a> also exist, and in this article I’ll show how to use them.</p>

<!--more-->

<p>Say we have a <a href="https://doc.rust-lang.org/std/collections/struct.HashMap.html" rel="external"><code class="language-plaintext highlighter-rouge">HashMap</code></a> and we want to add more than one value type to it.</p>

<p>For example:</p>

<div class="language-rust highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">use</span> <span class="nn">std</span><span class="p">::</span><span class="nn">collections</span><span class="p">::</span><span class="n">HashMap</span><span class="p">;</span>

<span class="k">fn</span> <span class="nf">main</span><span class="p">()</span> <span class="p">{</span>
    <span class="k">let</span> <span class="k">mut</span> <span class="n">map</span> <span class="o">=</span> <span class="nn">HashMap</span><span class="p">::</span><span class="nf">new</span><span class="p">();</span>

    <span class="n">map</span><span class="nf">.insert</span><span class="p">(</span><span class="s">"a"</span><span class="p">,</span> <span class="s">"1"</span><span class="p">);</span>
    <span class="n">map</span><span class="nf">.insert</span><span class="p">(</span><span class="s">"b"</span><span class="p">,</span> <span class="s">"2"</span><span class="p">);</span>

    <span class="k">for</span> <span class="p">(</span><span class="n">key</span><span class="p">,</span> <span class="n">value</span><span class="p">)</span> <span class="k">in</span> <span class="o">&amp;</span><span class="n">map</span> <span class="p">{</span>
        <span class="nd">println!</span><span class="p">(</span><span class="s">"{}: {}"</span><span class="p">,</span> <span class="n">key</span><span class="p">,</span> <span class="n">value</span><span class="p">);</span>
    <span class="p">}</span>
<span class="p">}</span>
</code></pre></div></div>

<p>This prints:</p>

<div class="language-rust highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="n">a</span><span class="p">:</span> <span class="mi">1</span>
<span class="n">b</span><span class="p">:</span> <span class="mi">2</span>
</code></pre></div></div>

<p>In the example above, the type of <code class="language-plaintext highlighter-rouge">map</code> is <code class="language-plaintext highlighter-rouge">HashMap&lt;&amp;str, &amp;str&gt;</code>. In other words, both keys and values are of type <code class="language-plaintext highlighter-rouge">&amp;str</code>.
What if we want the values to be of type <code class="language-plaintext highlighter-rouge">&amp;str</code> <em>and</em>, say, <code class="language-plaintext highlighter-rouge">i32</code>?</p>

<p>This won’t work:</p>

<div class="language-rust highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">use</span> <span class="nn">std</span><span class="p">::</span><span class="nn">collections</span><span class="p">::</span><span class="n">HashMap</span><span class="p">;</span>

<span class="k">fn</span> <span class="nf">main</span><span class="p">()</span> <span class="p">{</span>
    <span class="k">let</span> <span class="k">mut</span> <span class="n">map</span> <span class="o">=</span> <span class="nn">HashMap</span><span class="p">::</span><span class="nf">new</span><span class="p">();</span>

    <span class="n">map</span><span class="nf">.insert</span><span class="p">(</span><span class="s">"a"</span><span class="p">,</span> <span class="s">"1"</span><span class="p">);</span>
    <span class="n">map</span><span class="nf">.insert</span><span class="p">(</span><span class="s">"b"</span><span class="p">,</span> <span class="mi">2</span><span class="p">);</span>

    <span class="k">for</span> <span class="p">(</span><span class="n">key</span><span class="p">,</span> <span class="n">value</span><span class="p">)</span> <span class="k">in</span> <span class="o">&amp;</span><span class="n">map</span> <span class="p">{</span>
        <span class="nd">println!</span><span class="p">(</span><span class="s">"{}: {}"</span><span class="p">,</span> <span class="n">key</span><span class="p">,</span> <span class="n">value</span><span class="p">);</span>
    <span class="p">}</span>
<span class="p">}</span>
</code></pre></div></div>

<p>If we try it, we get this compile time error:</p>

<div class="language-rust highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="n">error</span><span class="p">[</span><span class="n">E0308</span><span class="p">]:</span> <span class="n">mismatched</span> <span class="n">types</span>
  <span class="o">-</span><span class="k">-&gt;</span> <span class="n">src</span><span class="o">/</span><span class="n">main</span><span class="py">.rs</span>

     <span class="n">map</span><span class="nf">.insert</span><span class="p">(</span><span class="s">"b"</span><span class="p">,</span> <span class="mi">2</span><span class="p">);</span>
                     <span class="o">^</span> <span class="n">expected</span> <span class="err">`</span><span class="o">&amp;</span><span class="nb">str</span><span class="err">`</span><span class="p">,</span> <span class="n">found</span> <span class="n">integer</span>
</code></pre></div></div>

<p>So how do we <strong>insert multiple value types</strong> in a <code class="language-plaintext highlighter-rouge">HashMap</code>? We have several options, each of them with its own trade-offs.</p>

<h2 id="option-1-use-an-enum">Option #1: Use an <code class="language-plaintext highlighter-rouge">enum</code></h2>

<p>We can define our own <a href="https://doc.rust-lang.org/std/keyword.enum.html" rel="external"><code class="language-plaintext highlighter-rouge">enum</code></a> to model our value type, and insert that into the hashmap:</p>

<div class="language-rust highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">use</span> <span class="nn">std</span><span class="p">::</span><span class="nn">collections</span><span class="p">::</span><span class="n">HashMap</span><span class="p">;</span>

<span class="nd">#[derive(Debug)]</span>
<span class="k">enum</span> <span class="n">Value</span> <span class="p">{</span>
    <span class="nf">Str</span><span class="p">(</span><span class="o">&amp;</span><span class="k">'static</span> <span class="nb">str</span><span class="p">),</span>
    <span class="nf">Int</span><span class="p">(</span><span class="nb">i32</span><span class="p">),</span>
<span class="p">}</span>

<span class="k">fn</span> <span class="nf">main</span><span class="p">()</span> <span class="p">{</span>
    <span class="k">let</span> <span class="k">mut</span> <span class="n">map</span> <span class="o">=</span> <span class="nn">HashMap</span><span class="p">::</span><span class="nf">new</span><span class="p">();</span>

    <span class="n">map</span><span class="nf">.insert</span><span class="p">(</span><span class="s">"a"</span><span class="p">,</span> <span class="nn">Value</span><span class="p">::</span><span class="nf">Str</span><span class="p">(</span><span class="s">"1"</span><span class="p">));</span>
    <span class="n">map</span><span class="nf">.insert</span><span class="p">(</span><span class="s">"b"</span><span class="p">,</span> <span class="nn">Value</span><span class="p">::</span><span class="nf">Int</span><span class="p">(</span><span class="mi">2</span><span class="p">));</span>

    <span class="k">for</span> <span class="p">(</span><span class="n">key</span><span class="p">,</span> <span class="n">value</span><span class="p">)</span> <span class="k">in</span> <span class="o">&amp;</span><span class="n">map</span> <span class="p">{</span>
        <span class="nd">println!</span><span class="p">(</span><span class="s">"{}: {:?}"</span><span class="p">,</span> <span class="n">key</span><span class="p">,</span> <span class="n">value</span><span class="p">);</span>
    <span class="p">}</span>
<span class="p">}</span>
</code></pre></div></div>

<p>This prints:</p>

<div class="language-rust highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="n">a</span><span class="p">:</span> <span class="nf">Str</span><span class="p">(</span><span class="s">"1"</span><span class="p">)</span>
<span class="n">b</span><span class="p">:</span> <span class="nf">Int</span><span class="p">(</span><span class="mi">2</span><span class="p">)</span>
</code></pre></div></div>

<p>This is similar to a <a href="https://doc.rust-lang.org/reference/items/unions.html" rel="external">union type</a>. By inserting values of type <code class="language-plaintext highlighter-rouge">Value::*</code>, we are effectively saying that the map can accept types that are either string, integer, or any other composite type we wish to add.</p>

<h2 id="option-2-use-a-box">Option #2: Use a <code class="language-plaintext highlighter-rouge">Box</code></h2>

<p>We can wrap our types in the <a href="https://doc.rust-lang.org/std/boxed/struct.Box.html" rel="external" title="std::boxed::Box"><code class="language-plaintext highlighter-rouge">Box</code></a> struct:</p>

<div class="language-rust highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">use</span> <span class="nn">std</span><span class="p">::</span><span class="nn">collections</span><span class="p">::</span><span class="n">HashMap</span><span class="p">;</span>

<span class="k">fn</span> <span class="nf">main</span><span class="p">()</span> <span class="p">{</span>
    <span class="k">let</span> <span class="k">mut</span> <span class="n">map</span> <span class="o">=</span> <span class="nn">HashMap</span><span class="p">::</span><span class="nf">new</span><span class="p">();</span>

    <span class="n">map</span><span class="nf">.insert</span><span class="p">(</span><span class="s">"a"</span><span class="p">,</span> <span class="nn">Box</span><span class="p">::</span><span class="nf">new</span><span class="p">(</span><span class="s">"1"</span><span class="p">));</span>
    <span class="n">map</span><span class="nf">.insert</span><span class="p">(</span><span class="s">"b"</span><span class="p">,</span> <span class="nn">Box</span><span class="p">::</span><span class="nf">new</span><span class="p">(</span><span class="mi">2</span><span class="p">));</span>

    <span class="k">for</span> <span class="p">(</span><span class="n">key</span><span class="p">,</span> <span class="n">value</span><span class="p">)</span> <span class="k">in</span> <span class="o">&amp;</span><span class="n">map</span> <span class="p">{</span>
        <span class="nd">println!</span><span class="p">(</span><span class="s">"{}: {}"</span><span class="p">,</span> <span class="n">key</span><span class="p">,</span> <span class="n">value</span><span class="p">);</span>
    <span class="p">}</span>
<span class="p">}</span>
</code></pre></div></div>

<p>This doesn’t compile right away. If we try to run this, we get a “mismatched types” error:</p>

<div class="language-rust highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="n">error</span><span class="p">[</span><span class="n">E0308</span><span class="p">]:</span> <span class="n">mismatched</span> <span class="n">types</span>
<span class="o">-</span><span class="k">-&gt;</span> <span class="n">src</span><span class="o">/</span><span class="n">main</span><span class="py">.rs</span>

    <span class="n">map</span><span class="nf">.insert</span><span class="p">(</span><span class="s">"b"</span><span class="p">,</span> <span class="nn">Box</span><span class="p">::</span><span class="nf">new</span><span class="p">(</span><span class="mi">2</span><span class="p">));</span>
                             <span class="o">^</span> <span class="n">expected</span> <span class="err">`</span><span class="o">&amp;</span><span class="nb">str</span><span class="err">`</span><span class="p">,</span> <span class="n">found</span> <span class="n">integer</span>
</code></pre></div></div>

<p>Luckily we can fix this by explicitly declaring the type of our map:</p>

<div class="language-rust highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">let</span> <span class="k">mut</span> <span class="n">map</span><span class="p">:</span> <span class="n">HashMap</span><span class="o">&lt;&amp;</span><span class="nb">str</span><span class="p">,</span> <span class="nb">Box</span><span class="o">&lt;</span><span class="k">dyn</span> <span class="n">Display</span> <span class="o">+</span> <span class="k">'static</span><span class="o">&gt;&gt;</span> <span class="o">=</span> <span class="nn">HashMap</span><span class="p">::</span><span class="nf">new</span><span class="p">();</span>
</code></pre></div></div>

<p>This works because we are actually storing instances of <code class="language-plaintext highlighter-rouge">Box</code>, not primitive types; <code class="language-plaintext highlighter-rouge">dyn Display</code> means the type of the <em>trait object</em> <code class="language-plaintext highlighter-rouge">Display</code>. In this case, <code class="language-plaintext highlighter-rouge">Display</code> happens to be a common trait between <code class="language-plaintext highlighter-rouge">&amp;str</code> and <code class="language-plaintext highlighter-rouge">i32</code>.</p>

<div class="language-rust highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">use</span> <span class="nn">std</span><span class="p">::</span><span class="nn">collections</span><span class="p">::</span><span class="n">HashMap</span><span class="p">;</span>
<span class="k">use</span> <span class="nn">std</span><span class="p">::</span><span class="nn">fmt</span><span class="p">::</span><span class="n">Display</span><span class="p">;</span>

<span class="k">fn</span> <span class="nf">main</span><span class="p">()</span> <span class="p">{</span>
    <span class="k">let</span> <span class="k">mut</span> <span class="n">map</span><span class="p">:</span> <span class="n">HashMap</span><span class="o">&lt;&amp;</span><span class="nb">str</span><span class="p">,</span> <span class="nb">Box</span><span class="o">&lt;</span><span class="k">dyn</span> <span class="n">Display</span> <span class="o">+</span> <span class="k">'static</span><span class="o">&gt;&gt;</span> <span class="o">=</span> <span class="nn">HashMap</span><span class="p">::</span><span class="nf">new</span><span class="p">();</span>

    <span class="n">map</span><span class="nf">.insert</span><span class="p">(</span><span class="s">"a"</span><span class="p">,</span> <span class="nn">Box</span><span class="p">::</span><span class="nf">new</span><span class="p">(</span><span class="s">"1"</span><span class="nf">.to_string</span><span class="p">()));</span>
    <span class="n">map</span><span class="nf">.insert</span><span class="p">(</span><span class="s">"b"</span><span class="p">,</span> <span class="nn">Box</span><span class="p">::</span><span class="nf">new</span><span class="p">(</span><span class="mi">2</span><span class="p">));</span>

    <span class="k">for</span> <span class="p">(</span><span class="n">key</span><span class="p">,</span> <span class="n">value</span><span class="p">)</span> <span class="k">in</span> <span class="o">&amp;</span><span class="n">map</span> <span class="p">{</span>
        <span class="nd">println!</span><span class="p">(</span><span class="s">"{}: {}"</span><span class="p">,</span> <span class="n">key</span><span class="p">,</span> <span class="n">value</span><span class="p">);</span>
    <span class="p">}</span>
<span class="p">}</span>
</code></pre></div></div>

<p>You may wonder what would happen if we were to use the type <code class="language-plaintext highlighter-rouge">dyn Display</code> without the <code class="language-plaintext highlighter-rouge">Box</code> wrapper. If we try that, we’d get this nasty error:</p>

<div class="language-rust highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="n">error</span><span class="p">[</span><span class="n">E0277</span><span class="p">]:</span> <span class="n">the</span> <span class="n">size</span> <span class="k">for</span> <span class="n">values</span> <span class="n">of</span> <span class="k">type</span> <span class="err">`</span><span class="p">(</span><span class="k">dyn</span> <span class="nn">std</span><span class="p">::</span><span class="nn">fmt</span><span class="p">::</span><span class="n">Display</span> <span class="o">+</span> <span class="k">'static</span><span class="p">)</span><span class="err">`</span> <span class="n">cannot</span> <span class="n">be</span> <span class="n">known</span> <span class="n">at</span> <span class="n">compilation</span> <span class="n">time</span>
   <span class="o">-</span><span class="k">-&gt;</span> <span class="n">src</span><span class="o">/</span><span class="n">main</span><span class="py">.rs</span>

     <span class="k">let</span> <span class="k">mut</span> <span class="n">map</span><span class="p">:</span> <span class="n">HashMap</span><span class="o">&lt;&amp;</span><span class="nb">str</span><span class="p">,</span> <span class="p">(</span><span class="k">dyn</span> <span class="n">Display</span> <span class="o">+</span> <span class="k">'static</span><span class="p">)</span><span class="o">&gt;</span> <span class="o">=</span> <span class="nn">HashMap</span><span class="p">::</span><span class="nf">new</span><span class="p">();</span>
                  <span class="o">^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^</span> <span class="n">doesn</span><span class="nv">'t</span> <span class="n">have</span> <span class="n">a</span> <span class="n">size</span> <span class="n">known</span> <span class="n">at</span> <span class="n">compile</span><span class="o">-</span><span class="n">time</span>

    <span class="o">=</span> <span class="n">help</span><span class="p">:</span> <span class="n">the</span> <span class="k">trait</span> <span class="err">`</span><span class="nn">std</span><span class="p">::</span><span class="nn">marker</span><span class="p">::</span><span class="nb">Sized</span><span class="err">`</span> <span class="n">is</span> <span class="n">not</span> <span class="n">implemented</span> <span class="k">for</span> <span class="err">`</span><span class="p">(</span><span class="k">dyn</span> <span class="nn">std</span><span class="p">::</span><span class="nn">fmt</span><span class="p">::</span><span class="n">Display</span> <span class="o">+</span> <span class="k">'static</span><span class="p">)</span><span class="err">`</span>
    <span class="o">=</span> <span class="n">note</span><span class="p">:</span> <span class="n">to</span> <span class="n">learn</span> <span class="n">more</span><span class="p">,</span> <span class="n">visit</span> <span class="o">&lt;</span><span class="n">https</span><span class="p">:</span><span class="c1">//doc.rust-lang.org/book/ch19-04-advanced-types.html#dynamically-sized-types-and-the-sized-trait&gt;</span>
    <span class="o">=</span> <span class="n">note</span><span class="p">:</span> <span class="n">required</span> <span class="n">by</span> <span class="err">`</span><span class="nn">std</span><span class="p">::</span><span class="nn">collections</span><span class="p">::</span><span class="n">HashMap</span>
</code></pre></div></div>

<p>This error may be confusing at first, but it actually makes sense. <a href="https://doc.rust-lang.org/book/" rel="external">The Rust Programming Language book</a> explains this very well in the <a href="https://doc.rust-lang.org/book/ch19-04-advanced-types.html" rel="external">Advanced Types</a> chapter:</p>

<blockquote>
  <p>“Rust needs to know how much memory to allocate for any value of a particular type, and all values of a type must use the same amount of memory.”</p>
</blockquote>

<p>The <code class="language-plaintext highlighter-rouge">Box&lt;T&gt;</code> type is a <a href="https://doc.rust-lang.org/reference/types/pointer.html" rel="external"><em>pointer type</em></a>. It lets us allocate data on the heap rather than the stack, and keeps a reference to the data in the stack in the form of a pointer, which is of fixed size.</p>

<h2 id="not-an-option-3-use-separate-maps-for-each-type">(Not an) Option #3: Use separate maps for each type</h2>

<p>Here we’re not actually using a <code class="language-plaintext highlighter-rouge">HashMap</code> with separate types, but rather two maps, each with its own type. It’s a bit more verbose and perhaps not the solution you’re looking for, but it’s worth keeping in mind that this works too:</p>

<div class="language-rust highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">use</span> <span class="nn">std</span><span class="p">::</span><span class="nn">collections</span><span class="p">::</span><span class="n">HashMap</span><span class="p">;</span>

<span class="k">fn</span> <span class="nf">main</span><span class="p">()</span> <span class="p">{</span>
    <span class="k">let</span> <span class="k">mut</span> <span class="n">strings_map</span> <span class="o">=</span> <span class="nn">HashMap</span><span class="p">::</span><span class="nf">new</span><span class="p">();</span>
    <span class="k">let</span> <span class="k">mut</span> <span class="n">integers_map</span> <span class="o">=</span> <span class="nn">HashMap</span><span class="p">::</span><span class="nf">new</span><span class="p">();</span>

    <span class="n">strings_map</span><span class="nf">.insert</span><span class="p">(</span><span class="s">"a"</span><span class="p">,</span> <span class="s">"1"</span><span class="p">);</span>
    <span class="n">integers_map</span><span class="nf">.insert</span><span class="p">(</span><span class="s">"b"</span><span class="p">,</span> <span class="mi">2</span><span class="p">);</span>

    <span class="k">for</span> <span class="p">(</span><span class="n">key</span><span class="p">,</span> <span class="n">value</span><span class="p">)</span> <span class="k">in</span> <span class="o">&amp;</span><span class="n">strings_map</span> <span class="p">{</span>
        <span class="nd">println!</span><span class="p">(</span><span class="s">"{}: {}"</span><span class="p">,</span> <span class="n">key</span><span class="p">,</span> <span class="n">value</span><span class="p">);</span>
    <span class="p">}</span>

    <span class="k">for</span> <span class="p">(</span><span class="n">key</span><span class="p">,</span> <span class="n">value</span><span class="p">)</span> <span class="k">in</span> <span class="o">&amp;</span><span class="n">integers_map</span> <span class="p">{</span>
        <span class="nd">println!</span><span class="p">(</span><span class="s">"{}: {}"</span><span class="p">,</span> <span class="n">key</span><span class="p">,</span> <span class="n">value</span><span class="p">);</span>
    <span class="p">}</span>
<span class="p">}</span>
</code></pre></div></div>

<p>It feels much simpler! And the output is naturally the same:</p>

<div class="language-rust highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="n">a</span><span class="p">:</span> <span class="mi">1</span>
<span class="n">b</span><span class="p">:</span> <span class="mi">2</span>
</code></pre></div></div>

<h2 id="conclusion">Conclusion</h2>

<p>Rust is very strict when it comes to polymorphic types. As you’ve seen, there are ways to achieve it, but they don’t feel as straightforward as with other dynamic languages such as Ruby or Python. Sometimes though it’s useful to take one step back and look at the actual problem we’re trying to solve. Once I did that, I realized that I didn’t necessarily have to limit myself to a single data structure, so I went for the last option.</p>

<p>I’m still a beginner with Rust, so I might have missed a better solution. <a href="https://doc.rust-lang.org/book/ch17-02-trait-objects.html" rel="external">Trait Objects</a> could be one: I’ve experimented with them, but they weren’t quite what I was looking for. If you have any suggestions or know of other possible solutions, feel free to comment below!</p>

<hr />

<p><strong>Update</strong>: <a href="https://twitter.com/alilleybrinker/status/1280185393258926088" rel="external">@alilleybrinker</a> on Twitter pointed out two caveats to be aware of. One is about the meaning of the <code class="language-plaintext highlighter-rouge">'static</code> <em>bound</em>: when used on a generic type, any references inside the type must live as long as <code class="language-plaintext highlighter-rouge">'static</code>. However, by adding <code class="language-plaintext highlighter-rouge">'static</code> we are also effectively saying that the values inside the <code class="language-plaintext highlighter-rouge">Box</code> won’t contain references. The other caveat is that, when using <code class="language-plaintext highlighter-rouge">dyn Display</code>, the original types are erased, so the available methods are only those known from the <code class="language-plaintext highlighter-rouge">Display</code> trait.</p>

<p><strong>Update #2</strong>: Fixed typos and re-enabled comments.</p>
]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[How to fix “Untracked working tree would be overwritten by merge” error]]></title>
    <link href="https://simonewebdesign.it/how-to-fix-untracked-working-tree-would-be-overwritten-by-merge-error/"/>
    <updated>2020-06-25T00:00:00+00:00</updated>
    <id>https://simonewebdesign.it/how-to-fix-untracked-working-tree-would-be-overwritten-by-merge-error</id>
    <content type="html"><![CDATA[<p>Let’s say you have two Git repositories: one on GitHub, and one on your computer.<br />They contain <strong>identical</strong> (or very similar) files, and what you want to do is “synchronize” them (i.e. make them look exactly the same). Maybe all you need is to download a few missing files from GitHub to your computer, or simply push some changes from your machine to GitHub.</p>

<p>You have tried <code class="language-plaintext highlighter-rouge">git pull</code>, but you’re getting this error:</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>error: Untracked working tree file * would be overwritten by merge.
fatal: read-tree failed
</code></pre></div></div>

<p>You need the changes, but obviously you don’t want to overwrite or lose any files. Don’t worry, the fix is actually straightforward!</p>

<!--more-->

<h2 id="why-am-i-seeing-this-error">Why am I seeing this error?</h2>

<p>The reason is probably because you didn’t <strong>clone</strong> the repository. In my case, I already had some local files, so instead of running <code class="language-plaintext highlighter-rouge">git clone</code>, here’s what I did:</p>

<div class="language-bash highlighter-rouge"><div class="highlight"><pre class="highlight"><code>git init
git remote add origin git@github.com:&lt;username&gt;/&lt;reponame&gt;.git
</code></pre></div></div>

<p>If you try to <code class="language-plaintext highlighter-rouge">git pull origin &lt;branch-name&gt;</code>, you might get the “untracked working tree” error.</p>

<h2 id="how-do-i-fix-it">How do I fix it?</h2>

<p>If you have already tried pulling from the remote and it didn’t work, <strong>here’s the fix</strong>:</p>

<div class="language-bash highlighter-rouge"><div class="highlight"><pre class="highlight"><code>git branch <span class="nt">--track</span> &lt;branch-name&gt; origin/&lt;branch-name&gt;
</code></pre></div></div>

<p>For example, if your branch is named <code class="language-plaintext highlighter-rouge">main</code>:</p>

<div class="language-bash highlighter-rouge"><div class="highlight"><pre class="highlight"><code>git branch <span class="nt">--track</span> main origin/main
</code></pre></div></div>

<p>What this does is simply tell Git that these two branches, <code class="language-plaintext highlighter-rouge">main</code> and <code class="language-plaintext highlighter-rouge">origin/main</code>, are related to each other, and that it should keep track of the changes between them. Turns out it also fixes the error, since Git can now <em>see</em> that nothing would be overwritten.</p>

<h2 id="wait--thats-it">Wait — that’s it?</h2>

<p>Yes! After running the command above, <code class="language-plaintext highlighter-rouge">git status</code> will indeed reveal the differences between the two repositories: your untracked files (i.e. extra files that you only have on your PC) will still be there, and some other files may have been automatically staged for deletion: these are files that are present in the remote repo, but you don’t have locally.</p>

<p>At this point you’ll want to double-check that everything is the way it should be. You may also want to run:</p>

<div class="language-bash highlighter-rouge"><div class="highlight"><pre class="highlight"><code>git reset
</code></pre></div></div>

<p>To get a clean state. Don’t worry, this won’t delete anything at all, it will simply unstage any modification that was applied automatically by Git. You can stage back the changes you care about using <code class="language-plaintext highlighter-rouge">git add .</code> — once you are happy, you can finally make a commit and run:</p>

<div class="language-bash highlighter-rouge"><div class="highlight"><pre class="highlight"><code>git push
</code></pre></div></div>

<p>Note there’s no need to specify the origin and the branch name anymore, since the two branches (the local and the remote) are now tracked.</p>

<hr />

<p>Hopefully this article helped you fix your issue; either way, feel free to ask for help by leaving a comment below.</p>

<p>Happy hacking!</p>
]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[How to enable Dark Mode on macOS with the command line]]></title>
    <link href="https://simonewebdesign.it/how-to-enable-dark-mode-macos-command-line/"/>
    <updated>2020-04-28T00:00:00+00:00</updated>
    <id>https://simonewebdesign.it/how-to-enable-dark-mode-macos-command-line</id>
    <content type="html"><![CDATA[<p>If you want to toggle between light and dark mode, it can be done with a single shell command:</p>

<div class="language-applescript highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="nv">osascript</span><span class="w"> </span><span class="o">-</span><span class="nv">e</span><span class="w"> </span><span class="err">'</span><span class="k">tell</span><span class="w"> </span><span class="nv">app</span><span class="w"> </span><span class="s2">"System Events"</span><span class="w"> </span><span class="k">to</span><span class="w"> </span><span class="k">tell</span><span class="w"> </span><span class="nv">appearance</span><span class="w"> </span><span class="nv">preferences</span><span class="w"> </span><span class="k">to</span><span class="w"> </span><span class="k">set</span><span class="w"> </span><span class="nv">dark</span><span class="w"> </span><span class="nv">mode</span><span class="w"> </span><span class="k">to</span><span class="w"> </span><span class="ow">not</span><span class="w"> </span><span class="nv">dark</span><span class="w"> </span><span class="nv">mode</span><span class="err">'</span><span class="w">
</span></code></pre></div></div>

<p>Try it and it will switch the mode immediately. No need to restart or install anything.</p>

<!--more-->

<h2 id="how-does-it-work">How does it work?</h2>

<p>It’s <a href="https://en.wikipedia.org/wiki/AppleScript" rel="external">AppleScript</a>. <code class="language-plaintext highlighter-rouge">dark mode</code> is a boolean value in the user defaults system. <code class="language-plaintext highlighter-rouge">not dark mode</code> is the opposite of that value. So, for example, if the value is <code class="language-plaintext highlighter-rouge">true</code>, it’s like saying <code class="language-plaintext highlighter-rouge">not true</code> (i.e. <code class="language-plaintext highlighter-rouge">false</code>), effectively acting like a light switch.</p>

<p>Enjoy the dark!</p>
]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[A pure CSS onclick context menu]]></title>
    <link href="https://simonewebdesign.it/pure-css-onclick-context-menu/"/>
    <updated>2019-05-13T00:00:00+00:00</updated>
    <id>https://simonewebdesign.it/pure-css-onclick-context-menu</id>
    <content type="html"><![CDATA[<p>
  Context menus are one of those very useful UI widgets that still haven't reached the HTML spec.
  <a href="https://developer.mozilla.org/en-US/docs/Web/HTML/Global_attributes/contextmenu" rel="external">There have been attempts</a>,
  but for now everyone tends to make their own custom implementation.
</p>

<p>Especially with the advent of React, the tendency is to write a custom menu component that uses JavaScript to open/close itself, perhaps by using an invisible overlay to detect clicks outside the menu and close it accordingly. This works fine in practice, however it doesn't have to be so complicated. If you need a simple <strong>dropdown menu</strong> that:</p>

<ul>
<li>Has no dependencies;
<li>Can be triggered with a click/tap on any element;
<li>Is fully cross-browser;
<li>Doesn't need JavaScript!
</ul>

<p>Then look no further. It's much simpler than you think!</p>

<!--more-->

<h2>An example</h2>

Try clicking this button: <button>☰</button><nav class="menu">
        <ul>
            <li>
                <button onclick="alert('Hello there!')">Display Greeting</button>
            </li>
            <li>
                <button onclick="print()">Print This Page</button>
            </li>
        </ul>
    </nav>

<p>This is done in <strong>pure HTML and CSS</strong>; the JavaScript is there just to add functionality. Source code below.</p>

<h3>The HTML</h3>

<figure class="highlight"><pre><code class="language-html" data-lang="html"><span class="nt">&lt;button&gt;</span>☰<span class="nt">&lt;/button&gt;</span>
<span class="nt">&lt;nav</span> <span class="na">class=</span><span class="s">"menu"</span><span class="nt">&gt;</span>
  <span class="nt">&lt;ul&gt;</span>
    <span class="nt">&lt;li&gt;</span>
      <span class="nt">&lt;button</span> <span class="na">onclick=</span><span class="s">"alert('Hello there!')"</span><span class="nt">&gt;</span>
        Display Greeting
      <span class="nt">&lt;/button&gt;</span>
    <span class="nt">&lt;/li&gt;</span>
    <span class="nt">&lt;li&gt;</span>
      <span class="nt">&lt;button</span> <span class="na">onclick=</span><span class="s">"print()"</span><span class="nt">&gt;</span>
        Print This Page
      <span class="nt">&lt;/button&gt;</span>
    <span class="nt">&lt;/li&gt;</span>
  <span class="nt">&lt;/ul&gt;</span>
<span class="nt">&lt;/nav&gt;</span></code></pre></figure>

<h3>The CSS</h3>

<figure class="highlight"><pre><code class="language-css" data-lang="css"><span class="nc">.menu</span> <span class="p">{</span>
    <span class="nl">visibility</span><span class="p">:</span> <span class="nb">hidden</span><span class="p">;</span>
<span class="p">}</span>

<span class="nt">button</span> <span class="o">+</span> <span class="nc">.menu</span><span class="nd">:active</span><span class="o">,</span>
<span class="nt">button</span><span class="nd">:focus</span> <span class="o">+</span> <span class="nc">.menu</span> <span class="p">{</span>
    <span class="nl">visibility</span><span class="p">:</span> <span class="nb">visible</span><span class="p">;</span>
<span class="p">}</span></code></pre></figure>

<p>That's the trick: we hide the menu in CSS initially, then show it when the button gets focused <em>and</em> while we're clicking on the menu itself. This is necessary so that the click actually gets registered. That's it! <strong>No JS trickery involved.</strong></p>

<p>You can attach event listeners to the menu items, e.g. using <a href=/onclick-vs-addeventlistener/><code>onclick</code> or <code>document.addEventListener</code></a> and they'll work as usual. You may also just use <code>&lt;a&gt;</code> tags instead of buttons, depending on your use case.</a></p>

<p>Naturally the menu can be opened only by elements that can receive focus, such as buttons and anchors. So what about other non-interactive elements? Can we make them focusable too? <strong>The answer is yes!</strong></p>

<h2>A more complicated example</h2>

<p>We want to <strong>display a context menu</strong> when clicking on the following image: <figure class="doge-demo" tabindex="-1">
  <picture class="doge">
    <source type="image/webp" srcset="/images/doge.webp">
    <img src="/images/doge.png" loading="lazy" width="300" height="300" alt="doge meme" title="Click me to open the menu..." />
  </picture>
  <figcaption>wow, this image is clickable!</figcaption>
  <nav class="menu">
    <ul>
      <li>
        <button onclick="alert('Button clicked!')">Open Image in New Tab</button>
      </li>
      <li>
        <button onclick="console.log(1)">Save Image As...</button>
      </li>
      <li>
        <button>Copy Image Address</button>
      </li>
    </ul>
  </nav>
</figure>

<h3>The HTML</h3>

<figure class="highlight"><pre><code class="language-html" data-lang="html"><span class="nt">&lt;figure</span> <span class="na">tabindex=</span><span class="s">"-1"</span><span class="nt">&gt;</span>
  <span class="nt">&lt;img</span> <span class="na">src=</span><span class="s">"/images/doge.png"</span> <span class="nt">/&gt;</span>

  <span class="nt">&lt;nav</span> <span class="na">class=</span><span class="s">"menu"</span><span class="nt">&gt;</span>
    <span class="nt">&lt;ul&gt;</span>
      <span class="nt">&lt;li&gt;</span>
        <span class="nt">&lt;button&gt;</span>Open Image in New Tab<span class="nt">&lt;/button&gt;</span>
      <span class="nt">&lt;/li&gt;</span>
      <span class="nt">&lt;li&gt;</span>
        <span class="nt">&lt;button&gt;</span>Save Image As...<span class="nt">&lt;/button&gt;</span>
      <span class="nt">&lt;/li&gt;</span>
      <span class="nt">&lt;li&gt;</span>
        <span class="nt">&lt;button&gt;</span>Copy Image Address<span class="nt">&lt;/button&gt;</span>
      <span class="nt">&lt;/li&gt;</span>
    <span class="nt">&lt;/ul&gt;</span>
  <span class="nt">&lt;/nav&gt;</span>
<span class="nt">&lt;/figure&gt;</span></code></pre></figure>

<p>The trick here was to add <a href="https://developer.mozilla.org/en-US/docs/Web/HTML/Global_attributes/tabindex" rel="external"><code>tabindex</code></a>. This makes the element focusable, so that it can open the menu on click. Note that if the clickable element is a <code>&lt;button&gt;</code> or other <a href="https://developer.mozilla.org/en-US/docs/Web/Guide/HTML/Content_categories#Interactive_content" rel="external">interactive content</a> (i.e. any focusable element), then you don't even need this!</p>

<p>I've used a <code>&lt;figure&gt;</code>, but you can use any element you like. Just add <code>tabindex="-1"</code> to make it focusable, if it isn't already. You can place the menu anywhere you want in the HTML, as long as you're able to target it with a CSS selector. Just try not to put a button in a button as that's invalid HTML, although technically it will still work.</p>

<h3>The CSS</h3>

<figure class="highlight"><pre><code class="language-css" data-lang="css"><span class="nc">.menu</span> <span class="p">{</span>
    <span class="nl">visibility</span><span class="p">:</span> <span class="nb">hidden</span><span class="p">;</span>
<span class="p">}</span>

<span class="nt">figure</span><span class="nd">:active</span> <span class="nc">.menu</span><span class="o">,</span>
<span class="nt">figure</span><span class="nd">:focus</span> <span class="nc">.menu</span> <span class="p">{</span>
    <span class="nl">visibility</span><span class="p">:</span> <span class="nb">visible</span><span class="p">;</span>
<span class="p">}</span></code></pre></figure>

<h3>How do I make the menu appear next to the mouse cursor?</h3>

<p>You'll need JavaScript, but it's entirely up to you whether you want to do this. Alternatively you could add <code>position: absolute</code> to the menu and <strong>just make it appear below (or next to) the element you clicked</strong> — no need for JS in this case! Anyway, this did the trick for me:</p>

<figure class="highlight"><pre><code class="language-javascript" data-lang="javascript"><span class="kd">const</span> <span class="nx">img</span> <span class="o">=</span> <span class="nb">document</span><span class="p">.</span><span class="nf">querySelector</span><span class="p">(</span><span class="dl">'</span><span class="s1">.doge</span><span class="dl">'</span><span class="p">);</span>
<span class="kd">const</span> <span class="nx">menu</span> <span class="o">=</span> <span class="nb">document</span><span class="p">.</span><span class="nf">querySelector</span><span class="p">(</span><span class="dl">'</span><span class="s1">.menu</span><span class="dl">'</span><span class="p">);</span>

<span class="nx">img</span><span class="p">.</span><span class="nf">addEventListener</span><span class="p">(</span><span class="dl">'</span><span class="s1">mousedown</span><span class="dl">'</span><span class="p">,</span> <span class="p">({</span> <span class="nx">offsetX</span><span class="p">,</span> <span class="nx">offsetY</span> <span class="p">})</span> <span class="o">=&gt;</span> <span class="p">{</span>
    <span class="nx">menu</span><span class="p">.</span><span class="nx">style</span><span class="p">.</span><span class="nx">top</span> <span class="o">=</span> <span class="nx">offsetY</span> <span class="o">+</span> <span class="dl">'</span><span class="s1">px</span><span class="dl">'</span><span class="p">;</span>
    <span class="nx">menu</span><span class="p">.</span><span class="nx">style</span><span class="p">.</span><span class="nx">left</span> <span class="o">=</span> <span class="nx">offsetX</span> <span class="o">+</span> <span class="dl">'</span><span class="s1">px</span><span class="dl">'</span><span class="p">;</span>
<span class="p">});</span></code></pre></figure>

<h3>I want the menu to close when I click the button again!</h3>

<p>If that's the case, you'll probably be better off using the old <a href="https://css-tricks.com/the-checkbox-hack/" rel="external">checkbox hack</a>.</p>

<h3>A note about accessibility</h3>

<p>Accessibility isn't the main focus of this article, but an important topic nonetheless. Menu items <strong>should be navigatable with a keyboard</strong>: this requires JS, but it's not hard to achieve. The <abbr title="World Wide Web Consortium">W3C</abbr> has done a lot of work around accessibility and there's plenty of examples you can refer to on their site: for instance, I think the <a href="https://www.w3.org/TR/2017/NOTE-wai-aria-practices-1.1-20171214/examples/menu-button/menu-button-links.html" rel="external">menu button example</a> is particularly relevant.</p>

<h3>What about browser support?</h3>

<p>It may not work in some very old browsers, so make sure to test it in the browsers you need to support. <a href="https://developer.mozilla.org/en-US/docs/Web/HTML/Element/button#Clicking_and_focus" rel="external">This MDN page</a> has some info about what happens to the focus of a button when being clicked/tapped on different platforms. I did some tests myself and it seems to work well everywhere, including IE and mobile browsers.</p>

<p><b>Update:</b> this blog post received a lot of attention and a few folks reached out to me about an issue, specifically with Safari and Firefox, on both iOS and macOS: the button won't focus. No worries though, it only affects buttons; other tags will work just fine. You may consider using <code>&lt;span tabindex=0&gt;</code> — the semantic meaning is lost entirely here, so if you really want to use a button, you can always focus it programmatically via JS, but <em>only</em> on Apple devices — for example:</p>

<figure class="highlight"><pre><code class="language-javascript" data-lang="javascript"><span class="k">if </span><span class="p">(</span>
  <span class="sr">/apple/i</span><span class="p">.</span><span class="nf">test</span><span class="p">(</span><span class="nb">navigator</span><span class="p">.</span><span class="nx">vendor</span><span class="p">)</span> <span class="o">||</span>
  <span class="sr">/Mac.*Firefox/</span><span class="p">.</span><span class="nf">test</span><span class="p">(</span><span class="nb">navigator</span><span class="p">.</span><span class="nx">userAgent</span><span class="p">)</span>
<span class="p">)</span> <span class="p">{</span>
  <span class="kd">const</span> <span class="nx">button</span> <span class="o">=</span> <span class="nb">document</span><span class="p">.</span><span class="nf">querySelector</span><span class="p">(</span><span class="dl">'</span><span class="s1">button</span><span class="dl">'</span><span class="p">);</span>

  <span class="nx">button</span><span class="p">.</span><span class="nf">addEventListener</span><span class="p">(</span><span class="dl">'</span><span class="s1">click</span><span class="dl">'</span><span class="p">,</span> <span class="nx">event</span> <span class="o">=&gt;</span> <span class="p">{</span>
    <span class="nx">event</span><span class="p">.</span><span class="nx">target</span><span class="p">.</span><span class="nf">focus</span><span class="p">();</span>
  <span class="p">});</span>
<span class="p">}</span></code></pre></figure>

<p>Another issue you may find specific to Apple is that the menu won't close when tapping outside of it. There's an easy fix: simply add <code>tabindex="-1"</code> to the container or the body tag.</p>

<hr>

<p>And that's it! I hope you found this useful. If you spot any issues, please do let me know!</p>

<script>
const img = document.querySelector('.doge');
const menu = document.querySelector('.doge-demo .menu');

img.addEventListener('mousedown', function (event) {
    const { offsetX, offsetY } = event;
    menu.style.top = offsetY + 'px';
    menu.style.left = offsetX + 'px';
});

if (
    /apple/i.test(navigator.vendor) ||
    /Mac.*Firefox/.test(navigator.userAgent)
) {
    document.querySelector('h2 + button').addEventListener('click', function (event) {
        event.target.focus();
    });
}

</script>


<style>
.entry-content h2 code {
  background: rgba(0, 0, 0, 0.05);
  padding: 0.1rem 0.2rem;
  border-radius: 4px;
}

.entry-content .doge-demo {
  position: relative;
  width: 306px;
  margin: 0 auto;
  outline: none;
}
.entry-content .doge-demo:active .menu, .entry-content .doge-demo:focus .menu {
  visibility: visible;
}
.entry-content .doge-demo img {
  margin-bottom: 0.5rem !important;
  border: 2px solid transparent;
  outline: 1px solid rgba(0, 0, 0, 0.5);
  cursor: pointer;
}
.entry-content .doge-demo img:active, .entry-content .doge-demo img:focus {
  border: 2px solid green;
}
.entry-content .doge-demo figcaption {
  text-align: center;
  background: rgba(0, 0, 0, 0.05);
  width: 306px;
  margin: 0 auto;
  margin-top: -11px;
  margin-left: -1px;
  font-size: 0.9rem;
  color: rgba(255, 255, 255, 0.96);
  background-color: rgba(0, 0, 0, 0.7);
}
.entry-content .doge-demo .menu {
  position: absolute;
  top: 0;
  left: 0;
  min-width: 14rem;
}

.entry-content .menu {
  visibility: hidden;
  background: white;
  border-radius: 4px;
  border: 1px solid #dedede;
}
.entry-content .menu > ul {
  list-style: none;
  margin: 0.4rem 0;
}
.entry-content .menu > ul > li {
  padding: 0;
}
.entry-content .menu > ul > li > button {
  padding: 0.2rem 0.8rem;
  width: 100%;
  font-size: 1rem;
  -webkit-appearance: button;
  -moz-appearance: button;
  text-transform: none;
  font-family: inherit;
  font-size: 100%;
  line-height: 1.15;
  margin: 0;
  overflow: visible;
  border: 0;
  text-align: left;
  font-family: Arial, Verdana, sans-serif;
  outline: none;
  cursor: pointer;
  background: transparent;
}
.entry-content .menu > ul > li > button:hover {
  background: rgba(0, 0, 0, 0.04);
}
.entry-content .menu > ul > li > button:active, .entry-content .menu > ul > li > button:focus {
  background: rgba(0, 0, 0, 0.08);
}

.entry-content button + .menu {
  display: inline-block;
  position: absolute;
}

.entry-content button + .menu:active {
  visibility: visible;
}

.entry-content button:focus + .menu {
  visibility: visible;
}
</style>
]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[Don't stop learning]]></title>
    <link href="https://simonewebdesign.it/dont-stop-learning/"/>
    <updated>2018-02-21T00:00:00+00:00</updated>
    <id>https://simonewebdesign.it/dont-stop-learning</id>
    <content type="html"><![CDATA[<p>Back in the days, when I got serious about becoming a "real programmer", I decided I wanted to learn Java.</p>

<p>I didn’t know anything about OOP, Design Patterns, Single Responsibility… all I knew was some PHP, Visual Basic, and database design stuff. That was it.</p>

<p>So I went to a book store and I bought this book about Object-Oriented Programming in Java 6. It was a massive book, probably around 1000 pages of code and programming best practices, and I read like 80% of it. Some parts were too advanced for me, but I learned a lot.</p>

<p>I used to like Java. I thought, “so this is what real programming looks like, with classes and inheritance. That’s the right way”.</p>

<p>I actually believed this for a while, until that day…</p>

<p>One day I went to this website, projecteuler.net, which is basically a way to prove your skills by solving difficult programming challenges, and learn in the process.</p>

<p>It was years ago, but I remember I solved the first couple exercises pretty easily. The third one was a bit harder. Here’s the original text:</p>

<blockquote>
  <p>A palindromic number reads the same both ways. The largest palindrome made from the product of two 2-digit numbers is 9009 = 91 × 99.</p>
  <p>Find the largest palindrome made from the product of two 3-digit numbers.</p>
</blockquote>

<p><small>Source: <a href="https://projecteuler.net/problem=4">https://projecteuler.net/problem=4</a></small></p>

<p>I spent a few hours on it before coming up with this:</p>

<div class="language-java highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kn">import</span> <span class="nn">static</span> <span class="n">java</span><span class="o">.</span><span class="na">lang</span><span class="o">.</span><span class="na">System</span><span class="o">.</span><span class="na">out</span><span class="o">;</span>

<span class="kn">import</span> <span class="nn">java.util.ArrayList</span><span class="o">;</span>
<span class="kn">import</span> <span class="nn">java.util.List</span><span class="o">;</span>

<span class="kd">public</span> <span class="kd">class</span> <span class="nc">Euler4</span>
<span class="o">{</span>
  <span class="kd">static</span> <span class="kd">final</span> <span class="kt">int</span> <span class="no">MIN</span> <span class="o">=</span> <span class="mi">100</span><span class="o">;</span>
  <span class="kd">static</span> <span class="kd">final</span> <span class="kt">int</span> <span class="no">MAX</span> <span class="o">=</span> <span class="mi">999</span><span class="o">;</span>

  <span class="kd">public</span> <span class="kd">static</span> <span class="nc">List</span><span class="o">&lt;</span><span class="nc">Integer</span><span class="o">&gt;</span> <span class="nf">getPalindromes</span><span class="o">(</span><span class="kt">int</span> <span class="n">min</span><span class="o">,</span> <span class="kt">int</span> <span class="n">max</span><span class="o">)</span>
  <span class="o">{</span>
    <span class="nc">List</span><span class="o">&lt;</span><span class="nc">Integer</span><span class="o">&gt;</span> <span class="n">palindromes</span> <span class="o">=</span> <span class="k">new</span> <span class="nc">ArrayList</span><span class="o">&lt;&gt;();</span>
    <span class="k">for</span> <span class="o">(</span><span class="kt">int</span> <span class="n">i</span><span class="o">=</span><span class="n">max</span><span class="o">;</span> <span class="n">i</span> <span class="o">&gt;=</span> <span class="n">min</span><span class="o">;</span> <span class="n">i</span><span class="o">--)</span>
    <span class="o">{</span>
      <span class="k">for</span> <span class="o">(</span><span class="kt">int</span> <span class="n">j</span><span class="o">=</span><span class="n">max</span><span class="o">;</span> <span class="n">j</span> <span class="o">&gt;=</span> <span class="n">min</span><span class="o">;</span> <span class="n">j</span><span class="o">--)</span>
      <span class="o">{</span>
        <span class="kt">int</span> <span class="n">product</span> <span class="o">=</span> <span class="n">i</span> <span class="o">*</span> <span class="n">j</span><span class="o">;</span>
        <span class="k">if</span> <span class="o">(</span><span class="n">isPalindrome</span><span class="o">(</span><span class="k">new</span> <span class="nc">Integer</span><span class="o">(</span><span class="n">product</span><span class="o">).</span><span class="na">toString</span><span class="o">()))</span>
          <span class="n">palindromes</span><span class="o">.</span><span class="na">add</span><span class="o">(</span><span class="n">product</span><span class="o">);</span>
      <span class="o">}</span>
    <span class="o">}</span>
    <span class="k">return</span> <span class="n">palindromes</span><span class="o">;</span>
  <span class="o">}</span>

  <span class="kd">public</span> <span class="kd">static</span> <span class="kt">boolean</span> <span class="nf">isPalindrome</span><span class="o">(</span><span class="nc">String</span> <span class="n">str</span><span class="o">)</span>
  <span class="o">{</span>
    <span class="k">if</span> <span class="o">(</span><span class="n">str</span><span class="o">.</span><span class="na">length</span><span class="o">()</span> <span class="o">&lt;</span> <span class="mi">0</span><span class="o">)</span> <span class="k">return</span> <span class="kc">false</span><span class="o">;</span>
    <span class="k">if</span> <span class="o">(</span><span class="n">str</span><span class="o">.</span><span class="na">length</span><span class="o">()</span> <span class="o">&lt;=</span> <span class="mi">1</span><span class="o">)</span> <span class="k">return</span> <span class="kc">true</span><span class="o">;</span>

    <span class="kt">char</span> <span class="n">firstChar</span> <span class="o">=</span> <span class="n">str</span><span class="o">.</span><span class="na">charAt</span><span class="o">(</span><span class="mi">0</span><span class="o">);</span>
    <span class="kt">char</span> <span class="n">lastChar</span> <span class="o">=</span> <span class="n">str</span><span class="o">.</span><span class="na">charAt</span><span class="o">(</span><span class="n">str</span><span class="o">.</span><span class="na">length</span><span class="o">()-</span><span class="mi">1</span><span class="o">);</span>

    <span class="k">if</span> <span class="o">(</span><span class="n">firstChar</span> <span class="o">==</span> <span class="n">lastChar</span><span class="o">)</span> <span class="o">{</span>
      <span class="k">return</span> <span class="nf">isPalindrome</span><span class="o">(</span><span class="n">str</span><span class="o">.</span><span class="na">substring</span><span class="o">(</span><span class="mi">1</span><span class="o">,</span> <span class="n">str</span><span class="o">.</span><span class="na">length</span><span class="o">()-</span><span class="mi">1</span><span class="o">));</span>
    <span class="o">}</span>
    <span class="k">return</span> <span class="kc">false</span><span class="o">;</span>
  <span class="o">}</span>

  <span class="kd">public</span> <span class="kd">static</span> <span class="kt">int</span> <span class="nf">getHighestNumber</span><span class="o">(</span><span class="nc">List</span><span class="o">&lt;</span><span class="nc">Integer</span><span class="o">&gt;</span> <span class="n">numbers</span><span class="o">)</span>
  <span class="o">{</span>
    <span class="kt">int</span> <span class="n">highestNumber</span> <span class="o">=</span> <span class="o">-</span><span class="mi">1</span><span class="o">;</span>
    <span class="k">for</span> <span class="o">(</span><span class="kt">int</span> <span class="n">number</span> <span class="o">:</span> <span class="n">numbers</span><span class="o">)</span>
      <span class="k">if</span> <span class="o">(</span><span class="n">number</span> <span class="o">&gt;</span> <span class="n">highestNumber</span><span class="o">)</span>
        <span class="n">highestNumber</span> <span class="o">=</span> <span class="n">number</span><span class="o">;</span>
    <span class="k">return</span> <span class="n">highestNumber</span><span class="o">;</span>
  <span class="o">}</span>

  <span class="kd">public</span> <span class="kd">static</span> <span class="kt">void</span> <span class="nf">main</span><span class="o">(</span><span class="nc">String</span><span class="o">[]</span> <span class="n">args</span><span class="o">)</span>
  <span class="o">{</span>
    <span class="nc">List</span><span class="o">&lt;</span><span class="nc">Integer</span><span class="o">&gt;</span> <span class="n">palindromes</span> <span class="o">=</span> <span class="n">getPalindromes</span><span class="o">(</span><span class="no">MIN</span><span class="o">,</span> <span class="no">MAX</span><span class="o">);</span>
    <span class="n">out</span><span class="o">.</span><span class="na">println</span><span class="o">(</span><span class="n">getHighestNumber</span><span class="o">(</span><span class="n">palindromes</span><span class="o">));</span>
  <span class="o">}</span>
<span class="o">}</span>
</code></pre></div></div>

<p>It’s 46 lines of code, without counting blank lines. Not too bad, right?</p>

<p>Ok, don’t be mean. I know that’s probably shitty code, but it was my own solution and I was quite proud of it.</p>

<p>Now, when you finish a challenge successfully, you’re given access to the forum, where other programmers post their own solutions in many different languages.</p>

<p>That’s where I first discovered <a href="/ruby-is-magic/">Ruby</a>.</p>

<p>I was reading the thread about the problem I just solved, when I stumbled across this Ruby solution:</p>

<div class="language-ruby highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="n">m</span> <span class="o">=</span> <span class="mi">0</span>
<span class="mi">901</span><span class="p">.</span><span class="nf">upto</span><span class="p">(</span><span class="mi">999</span><span class="p">)</span> <span class="p">{</span><span class="o">|</span><span class="n">a</span><span class="o">|</span>
  <span class="mi">901</span><span class="p">.</span><span class="nf">upto</span><span class="p">(</span><span class="mi">999</span><span class="p">){</span><span class="o">|</span><span class="n">b</span><span class="o">|</span>
    <span class="n">s</span> <span class="o">=</span> <span class="p">(</span><span class="n">a</span><span class="o">*</span><span class="n">b</span><span class="p">).</span><span class="nf">to_s</span>
    <span class="n">m</span> <span class="o">=</span> <span class="p">[</span><span class="n">m</span><span class="p">,</span> <span class="n">a</span><span class="o">*</span><span class="n">b</span><span class="p">].</span><span class="nf">max</span> <span class="k">if</span> <span class="n">s</span> <span class="o">==</span> <span class="n">s</span><span class="p">.</span><span class="nf">reverse</span>
  <span class="p">}</span>
<span class="p">}</span>
<span class="nb">puts</span> <span class="n">m</span>
</code></pre></div></div>

<p>And I was like, “wow, seriously? Only 8 lines of code?”.</p>

<p>I couldn’t believe my eyes. I was staring at something marvelous; some beauty that I never came across before.</p>

<p>Ruby is an object-oriented programming language that focuses on expressiveness and readability.</p>

<p>It was love at first sight. I started reading about this amazing language, about the fact that everything in Ruby is an object, even integers, and that you can write code like <code class="language-plaintext highlighter-rouge">3.times { print "Hello" }</code> to simply print “Hello” 3 times. It was like reading English, and I felt truly amazed, humbled, and inspired.</p>

<hr />

<p>Anyway, that’s just part of my story about becoming a better programmer. I’m not sure what the point is, I just felt like writing it down. But if, like me, you’re one of those people that need some ‘takeaway’ from a story, I guess it should be this:</p>

<blockquote>
  <p>Just don't stop learning, ever.</p>
  <p>Keep on learning and practicing, and you too will discover beautiful things.</p>
</blockquote>
]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[A Pipeable Logger]]></title>
    <link href="https://simonewebdesign.it/a-pipeable-logger/"/>
    <updated>2017-04-03T00:00:00+00:00</updated>
    <id>https://simonewebdesign.it/a-pipeable-logger</id>
    <content type="html"><![CDATA[<p>The Elixir Logger is pretty good. You can easily log anything with it, just call one of <code class="language-plaintext highlighter-rouge">debug</code>, <code class="language-plaintext highlighter-rouge">info</code>, <code class="language-plaintext highlighter-rouge">warn</code> or <code class="language-plaintext highlighter-rouge">error</code>. For example:</p>

<div class="language-elixir highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="no">Logger</span><span class="o">.</span><span class="n">info</span><span class="p">(</span><span class="s2">"something happened"</span><span class="p">)</span>
</code></pre></div></div>

<p>Turns into:</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>12:34:56.789 [info]  something happened
</code></pre></div></div>

<p>Very nice. However, there are cases where you may want to, say, change some data structure, like update a map or a list, and then log the transition, <strong>without breaking the pipe</strong>. Example:</p>

<div class="language-elixir highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">def</span> <span class="n">my_function</span> <span class="k">do</span>
  <span class="n">list</span> <span class="o">=</span> <span class="p">[</span><span class="mi">1</span><span class="p">,</span> <span class="mi">2</span><span class="p">,</span> <span class="mi">3</span><span class="p">]</span>

  <span class="n">list</span>
  <span class="o">|&gt;</span> <span class="no">Logger</span><span class="o">.</span><span class="n">debug</span><span class="p">(</span><span class="s2">"before insert: </span><span class="si">#{</span><span class="n">inspect</span> <span class="n">list</span><span class="si">}</span><span class="s2">"</span><span class="p">)</span>
  <span class="o">|&gt;</span> <span class="no">Enum</span><span class="o">.</span><span class="n">into</span><span class="p">([</span><span class="mi">0</span><span class="p">])</span>
  <span class="o">|&gt;</span> <span class="no">Logger</span><span class="o">.</span><span class="n">debug</span><span class="p">(</span><span class="s2">"after insert: </span><span class="si">#{</span><span class="n">inspect</span> <span class="n">list</span><span class="si">}</span><span class="s2">"</span><span class="p">)</span>
<span class="k">end</span>
</code></pre></div></div>

<p>This doesn’t work for many reasons. First, we can’t refer to <code class="language-plaintext highlighter-rouge">list</code> that way. If we do, we will always be logging <code class="language-plaintext highlighter-rouge">[1, 2, 3]</code>, because Elixir’s data structures are immutable.
Second, <code class="language-plaintext highlighter-rouge">Logger.*</code> functions return the <code class="language-plaintext highlighter-rouge">:ok</code> atom, which means you can’t use them in a pipe—unless that is what you want to return.</p>

<p>The solution to both issues is actually pretty straightforward: use a lambda!
A lambda is just an anonymous function. We can define it and call it right away. So the code above becomes:</p>

<div class="language-elixir highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">def</span> <span class="n">my_function</span> <span class="k">do</span>
  <span class="p">[</span><span class="mi">1</span><span class="p">,</span> <span class="mi">2</span><span class="p">,</span> <span class="mi">3</span><span class="p">]</span>
  <span class="o">|&gt;</span> <span class="p">(</span><span class="k">fn</span> <span class="n">list</span> <span class="o">-&gt;</span>
    <span class="no">Logger</span><span class="o">.</span><span class="n">debug</span><span class="p">(</span><span class="s2">"before insert: </span><span class="si">#{</span><span class="n">inspect</span> <span class="n">list</span><span class="si">}</span><span class="s2">"</span><span class="p">)</span>
    <span class="n">list</span>
  <span class="k">end</span><span class="p">)</span><span class="o">.</span><span class="p">()</span>
  <span class="o">|&gt;</span> <span class="no">Enum</span><span class="o">.</span><span class="n">into</span><span class="p">([</span><span class="mi">0</span><span class="p">])</span>
  <span class="o">|&gt;</span> <span class="p">(</span><span class="k">fn</span> <span class="n">list</span> <span class="o">-&gt;</span>
    <span class="no">Logger</span><span class="o">.</span><span class="n">debug</span><span class="p">(</span><span class="s2">"after insert: </span><span class="si">#{</span><span class="n">inspect</span> <span class="n">list</span><span class="si">}</span><span class="s2">"</span><span class="p">)</span>
    <span class="n">list</span>
  <span class="k">end</span><span class="p">)</span><span class="o">.</span><span class="p">()</span>
<span class="k">end</span>
</code></pre></div></div>

<p>If we call this function, we get:</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>12:34:56.789 [debug] before insert: [1, 2, 3]

12:34:56.823 [debug] after insert: [0, 1, 2, 3]
</code></pre></div></div>

<p>Great, exactly what we want! Except the syntax is horrible. But fear not, we can improve on it. How about we make a wrapper?</p>

<div class="language-elixir highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">defmodule</span> <span class="no">PipeableLogger</span> <span class="k">do</span>
  <span class="kn">require</span> <span class="no">Logger</span>

  <span class="k">def</span> <span class="n">debug</span><span class="p">(</span><span class="n">data</span><span class="p">,</span> <span class="n">msg</span><span class="p">)</span> <span class="k">do</span>
    <span class="no">Logger</span><span class="o">.</span><span class="n">debug</span><span class="p">(</span><span class="n">msg</span><span class="p">)</span>
    <span class="n">data</span>
  <span class="k">end</span>

  <span class="c1"># def warn, do: ...</span>
  <span class="c1"># def error, do: ...</span>
  <span class="c1"># def info, do: ...</span>
<span class="k">end</span>
</code></pre></div></div>

<p>Let’s rewrite our function once again:</p>

<div class="language-elixir highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">def</span> <span class="n">my_function</span> <span class="k">do</span>
  <span class="p">[</span><span class="mi">1</span><span class="p">,</span> <span class="mi">2</span><span class="p">,</span> <span class="mi">3</span><span class="p">]</span>
  <span class="o">|&gt;</span> <span class="p">(</span><span class="o">&amp;</span><span class="no">PipeableLogger</span><span class="o">.</span><span class="n">debug</span><span class="p">(</span><span class="nv">&amp;1</span><span class="p">,</span> <span class="s2">"before insert: </span><span class="si">#{</span><span class="n">inspect</span> <span class="nv">&amp;1</span><span class="si">}</span><span class="s2">"</span><span class="p">))</span><span class="o">.</span><span class="p">()</span>
  <span class="o">|&gt;</span> <span class="no">Enum</span><span class="o">.</span><span class="n">into</span><span class="p">([</span><span class="mi">0</span><span class="p">])</span>
  <span class="o">|&gt;</span> <span class="p">(</span><span class="o">&amp;</span><span class="no">PipeableLogger</span><span class="o">.</span><span class="n">debug</span><span class="p">(</span><span class="nv">&amp;1</span><span class="p">,</span> <span class="s2">"after insert: </span><span class="si">#{</span><span class="n">inspect</span> <span class="nv">&amp;1</span><span class="si">}</span><span class="s2">"</span><span class="p">))</span><span class="o">.</span><span class="p">()</span>
<span class="k">end</span>
</code></pre></div></div>

<p>Still not pretty though, as we still needed to wrap the function in a lambda. If we want to build a proper <code class="language-plaintext highlighter-rouge">Logger</code> wrapper, there are at least two different cases we may want to handle:</p>

<ol>
  <li>Logging a simple message (without any data);</li>
  <li>Logging the data we receive from the pipe, maybe also with a message.</li>
</ol>

<p>Here’s the improved version of <code class="language-plaintext highlighter-rouge">PipeableLogger</code>:</p>

<div class="language-elixir highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">defmodule</span> <span class="no">PipeableLogger</span> <span class="k">do</span>
  <span class="kn">require</span> <span class="no">Logger</span>

  <span class="k">def</span> <span class="n">debug</span><span class="p">(</span><span class="n">data</span><span class="p">,</span> <span class="n">msg</span> <span class="p">\\</span> <span class="s2">""</span><span class="p">,</span> <span class="n">metadata</span> <span class="p">\\</span> <span class="p">[])</span>
  <span class="k">def</span> <span class="n">debug</span><span class="p">(</span><span class="n">data</span><span class="p">,</span> <span class="n">msg</span><span class="p">,</span> <span class="n">metadata</span><span class="p">)</span> <span class="ow">when</span> <span class="n">msg</span> <span class="o">==</span> <span class="s2">""</span><span class="p">,</span> <span class="k">do</span><span class="p">:</span> <span class="no">Logger</span><span class="o">.</span><span class="n">debug</span><span class="p">(</span><span class="n">data</span><span class="p">,</span> <span class="n">metadata</span><span class="p">)</span>
  <span class="k">def</span> <span class="n">debug</span><span class="p">(</span><span class="n">data</span><span class="p">,</span> <span class="n">msg</span><span class="p">,</span> <span class="n">metadata</span><span class="p">)</span> <span class="k">do</span>
    <span class="no">Logger</span><span class="o">.</span><span class="n">debug</span><span class="p">(</span><span class="n">msg</span><span class="p">,</span> <span class="n">metadata</span><span class="p">)</span>
    <span class="n">data</span>
  <span class="k">end</span>

  <span class="c1"># def warn, do: ...</span>
  <span class="c1"># def error, do: ...</span>
  <span class="c1"># def info, do: ...</span>
<span class="k">end</span>
</code></pre></div></div>

<p>Let’s use it:</p>

<div class="language-elixir highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">def</span> <span class="n">my_function</span> <span class="k">do</span>
  <span class="p">[</span><span class="mi">1</span><span class="p">,</span> <span class="mi">2</span><span class="p">,</span> <span class="mi">3</span><span class="p">]</span>
  <span class="o">|&gt;</span> <span class="no">PipeableLogger</span><span class="o">.</span><span class="n">debug</span><span class="p">(</span><span class="s2">"before insert"</span><span class="p">)</span>
  <span class="o">|&gt;</span> <span class="no">Enum</span><span class="o">.</span><span class="n">into</span><span class="p">([</span><span class="mi">0</span><span class="p">])</span>
  <span class="o">|&gt;</span> <span class="no">PipeableLogger</span><span class="o">.</span><span class="n">debug</span><span class="p">(</span><span class="s2">"after insert"</span><span class="p">)</span>
<span class="k">end</span>
</code></pre></div></div>

<p>Much, much simpler! The only problem now is, we’re logging just a message. What if we want to log the data? It’s a lambda all over again.</p>

<p>Here’s the final version I came up with:</p>

<div class="language-elixir highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">defmodule</span> <span class="no">PipeableLogger</span> <span class="k">do</span>
  <span class="kn">require</span> <span class="no">Logger</span>

  <span class="k">def</span> <span class="n">debug</span><span class="p">(</span><span class="n">data</span><span class="p">,</span> <span class="n">msg</span> <span class="p">\\</span> <span class="s2">""</span><span class="p">,</span> <span class="n">metadata</span> <span class="p">\\</span> <span class="p">[])</span>
  <span class="k">def</span> <span class="n">debug</span><span class="p">(</span><span class="n">data</span><span class="p">,</span> <span class="n">msg</span><span class="p">,</span> <span class="n">metadata</span><span class="p">)</span> <span class="ow">when</span> <span class="n">msg</span> <span class="o">==</span> <span class="s2">""</span><span class="p">,</span> <span class="k">do</span><span class="p">:</span> <span class="no">Logger</span><span class="o">.</span><span class="n">debug</span><span class="p">(</span><span class="n">data</span><span class="p">,</span> <span class="n">metadata</span><span class="p">)</span>
  <span class="k">def</span> <span class="n">debug</span><span class="p">(</span><span class="n">data</span><span class="p">,</span> <span class="n">msg</span><span class="p">,</span> <span class="n">metadata</span><span class="p">)</span> <span class="ow">when</span> <span class="n">is_binary</span><span class="p">(</span><span class="n">data</span><span class="p">)</span> <span class="k">do</span>
    <span class="no">Logger</span><span class="o">.</span><span class="n">debug</span><span class="p">(</span><span class="n">msg</span> <span class="o">&lt;&gt;</span> <span class="n">data</span><span class="p">,</span> <span class="n">metadata</span><span class="p">)</span>
    <span class="n">data</span>
  <span class="k">end</span>
  <span class="k">def</span> <span class="n">debug</span><span class="p">(</span><span class="n">data</span><span class="p">,</span> <span class="n">msg</span><span class="p">,</span> <span class="n">metadata</span><span class="p">)</span> <span class="k">do</span>
    <span class="no">Logger</span><span class="o">.</span><span class="n">debug</span><span class="p">(</span><span class="n">msg</span> <span class="o">&lt;&gt;</span> <span class="n">inspect</span><span class="p">(</span><span class="n">data</span><span class="p">),</span> <span class="n">metadata</span><span class="p">)</span>
    <span class="n">data</span>
  <span class="k">end</span>

  <span class="c1"># def warn, do: ...</span>
  <span class="c1"># def error, do: ...</span>
  <span class="c1"># def info, do: ...</span>
<span class="k">end</span>
</code></pre></div></div>

<p>The assumption is that we always want to concatenate the data with the message, which is fair enough I think. Let’s see it in action:</p>

<div class="language-elixir highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">def</span> <span class="n">my_function</span> <span class="k">do</span>
  <span class="p">[</span><span class="mi">1</span><span class="p">,</span> <span class="mi">2</span><span class="p">,</span> <span class="mi">3</span><span class="p">]</span>
  <span class="o">|&gt;</span> <span class="no">PipeableLogger</span><span class="o">.</span><span class="n">debug</span><span class="p">(</span><span class="s2">"before insert: "</span><span class="p">)</span>
  <span class="o">|&gt;</span> <span class="no">Enum</span><span class="o">.</span><span class="n">into</span><span class="p">([</span><span class="mi">0</span><span class="p">])</span>
  <span class="o">|&gt;</span> <span class="no">PipeableLogger</span><span class="o">.</span><span class="n">debug</span><span class="p">(</span><span class="s2">"after insert: "</span><span class="p">)</span>
<span class="k">end</span>
</code></pre></div></div>

<div class="language-elixir highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="n">iex</span><span class="o">&gt;</span> <span class="n">my_function</span><span class="p">()</span>

<span class="mi">12</span><span class="p">:</span><span class="mi">34</span><span class="p">:</span><span class="mf">56.789</span> <span class="p">[</span><span class="n">debug</span><span class="p">]</span> <span class="n">before</span> <span class="ss">insert:</span> <span class="p">[</span><span class="mi">1</span><span class="p">,</span> <span class="mi">2</span><span class="p">,</span> <span class="mi">3</span><span class="p">]</span>

<span class="mi">12</span><span class="p">:</span><span class="mi">34</span><span class="p">:</span><span class="mf">56.789</span> <span class="p">[</span><span class="n">debug</span><span class="p">]</span> <span class="k">after</span> <span class="ss">insert:</span> <span class="p">[</span><span class="mi">0</span><span class="p">,</span> <span class="mi">1</span><span class="p">,</span> <span class="mi">2</span><span class="p">,</span> <span class="mi">3</span><span class="p">]</span>
<span class="p">[</span><span class="mi">0</span><span class="p">,</span> <span class="mi">1</span><span class="p">,</span> <span class="mi">2</span><span class="p">,</span> <span class="mi">3</span><span class="p">]</span>
</code></pre></div></div>

<p>Now we can log the data with a message, all in a pipe and without a lambda! Nice!</p>

<hr />

<p>Summing up, I’m not convinced a <code class="language-plaintext highlighter-rouge">Logger</code> wrapper is the right way. This kinda goes against the blog post, but to be fair I think Elixir people tend to use pipes way too much (I’m guilty as well). So I wouldn’t probably wrap <code class="language-plaintext highlighter-rouge">Logger</code> in any project.</p>

<p>It’s also worth noting that <code class="language-plaintext highlighter-rouge">Logger</code> supports the concept of metadata, which basically means you can already attach any data you want. For example, if you put this in your <code class="language-plaintext highlighter-rouge">config.exs</code>:</p>

<div class="language-elixir highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="n">config</span> <span class="ss">:logger</span><span class="p">,</span> <span class="ss">:console</span><span class="p">,</span>
  <span class="ss">metadata:</span> <span class="p">[</span><span class="ss">:my_list</span><span class="p">]</span>
</code></pre></div></div>

<p>You can then call <code class="language-plaintext highlighter-rouge">Logger</code> like this:</p>

<div class="language-elixir highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="n">iex</span><span class="p">(</span><span class="mi">1</span><span class="p">)</span><span class="o">&gt;</span> <span class="kn">require</span> <span class="no">Logger</span>
<span class="no">Logger</span>

<span class="n">iex</span><span class="p">(</span><span class="mi">2</span><span class="p">)</span><span class="o">&gt;</span> <span class="no">Logger</span><span class="o">.</span><span class="n">info</span> <span class="s2">"Work done"</span><span class="p">,</span> <span class="ss">my_list:</span> <span class="n">inspect</span> <span class="p">[</span><span class="mi">1</span><span class="p">,</span> <span class="mi">2</span><span class="p">,</span> <span class="mi">3</span><span class="p">]</span>

<span class="mi">12</span><span class="p">:</span><span class="mi">34</span><span class="p">:</span><span class="mf">56.789</span> <span class="n">my_list</span><span class="o">=</span><span class="p">[</span><span class="mi">1</span><span class="p">,</span> <span class="mi">2</span><span class="p">,</span> <span class="mi">3</span><span class="p">]</span> <span class="p">[</span><span class="n">info</span><span class="p">]</span>  <span class="no">Work</span> <span class="n">done</span>
<span class="ss">:ok</span>
</code></pre></div></div>

<p>Point is, you don’t need a wrapper if all you want is concatenate some data in the log message. You <em>do</em> need a wrapper though (or a lambda) if you want to use <code class="language-plaintext highlighter-rouge">Logger</code> in a pipe.</p>

<p>So how about this instead?</p>

<div class="language-elixir highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">def</span> <span class="n">my_function</span> <span class="k">do</span>
  <span class="n">list</span> <span class="o">=</span> <span class="p">[</span><span class="mi">1</span><span class="p">,</span> <span class="mi">2</span><span class="p">,</span> <span class="mi">3</span><span class="p">]</span>
  <span class="no">Logger</span><span class="o">.</span><span class="n">debug</span><span class="p">(</span><span class="s2">"before insert: </span><span class="si">#{</span><span class="n">inspect</span> <span class="n">list</span><span class="si">}</span><span class="s2">"</span><span class="p">)</span>
  <span class="n">new_list</span> <span class="o">=</span> <span class="no">Enum</span><span class="o">.</span><span class="n">into</span><span class="p">(</span><span class="n">list</span><span class="p">,</span> <span class="p">[</span><span class="mi">0</span><span class="p">])</span>
  <span class="no">Logger</span><span class="o">.</span><span class="n">debug</span><span class="p">(</span><span class="s2">"after insert: </span><span class="si">#{</span><span class="n">inspect</span> <span class="n">new_list</span><span class="si">}</span><span class="s2">"</span><span class="p">)</span>
<span class="k">end</span>
</code></pre></div></div>

<p><strong>Simple is better</strong>. It’s fine to break that pipe every once in a while!</p>
]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[Recursive Reduce in JavaScript and Clojure]]></title>
    <link href="https://simonewebdesign.it/recursive-reduce-in-javascript-and-clojure/"/>
    <updated>2016-07-26T13:00:00+00:00</updated>
    <id>https://simonewebdesign.it/recursive-reduce-in-javascript-and-clojure</id>
    <content type="html"><![CDATA[<p>Another fun kata:</p>

<blockquote>
  <p>Given an array of arbitrarily nested objects, return a flat array with all the objects marked as “good”.</p>
</blockquote>

<p>The definition above is quite generic, so I’ll provide examples to show
exactly what I mean.</p>

<p>The array in JavaScript looks like this:</p>

<div class="language-javascript highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kd">var</span> <span class="nx">items</span> <span class="o">=</span> <span class="p">[{</span>
    <span class="na">id</span><span class="p">:</span> <span class="mi">1</span><span class="p">,</span>
    <span class="na">good</span><span class="p">:</span> <span class="kc">true</span>
<span class="p">},</span> <span class="p">{</span>
    <span class="na">id</span><span class="p">:</span> <span class="mi">2</span><span class="p">,</span>
    <span class="na">children</span><span class="p">:</span> <span class="p">[{</span>
        <span class="na">id</span><span class="p">:</span> <span class="mi">3</span><span class="p">,</span>
        <span class="na">good</span><span class="p">:</span> <span class="kc">true</span>
    <span class="p">},</span> <span class="p">{</span>
        <span class="na">id</span><span class="p">:</span> <span class="mi">4</span><span class="p">,</span>
        <span class="na">good</span><span class="p">:</span> <span class="kc">true</span>
    <span class="p">},</span> <span class="p">{</span>
        <span class="na">id</span><span class="p">:</span> <span class="mi">5</span><span class="p">,</span>
        <span class="na">children</span><span class="p">:</span> <span class="p">[{</span>
                <span class="na">id</span><span class="p">:</span> <span class="mi">6</span><span class="p">,</span>
                <span class="na">good</span><span class="p">:</span> <span class="kc">true</span>
            <span class="p">}</span>
            <span class="p">...</span>
        <span class="p">]</span>
    <span class="p">},</span> <span class="p">{</span>
        <span class="na">id</span><span class="p">:</span> <span class="mi">9</span><span class="p">,</span>
        <span class="na">children</span><span class="p">:</span> <span class="p">[...]</span>
    <span class="p">},</span> <span class="p">...]</span>
<span class="p">},</span> <span class="p">...]</span>
</code></pre></div></div>

<p>We want the IDs of the good ones.</p>

<p>You might have noticed not all objects are “good”. Number 2 for example
is not good. So the result in this case should be:</p>

<div class="language-javascript highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="p">[</span><span class="mi">1</span><span class="p">,</span> <span class="mi">3</span><span class="p">,</span> <span class="mi">4</span><span class="p">,</span> <span class="mi">6</span><span class="p">]</span>
</code></pre></div></div>

<p>The only thing to notice here is that <strong>you know it’s not good because
it’s not marked as such.</strong> In other words, when some object is “bad”,
there’s no <code class="language-plaintext highlighter-rouge">good: false</code> nor <code class="language-plaintext highlighter-rouge">bad: true</code> that tells you that.</p>

<p>So how do we solve this challenge?</p>

<p>Since there’s an arbitrary nesting depth, we can once again leverage the
power and simplicity of recursion.</p>

<h2 id="solution-in-javascript">Solution in JavaScript</h2>

<p>I’ve created the function <code class="language-plaintext highlighter-rouge">goodOnes(items)</code> that takes the input and
returns what we expect. I’m also using <a href="https://github.com/ramda/ramda">Ramda.js</a>, just because I wanted a clean functional solution and I didn’t want to mess around
object mutation.</p>

<p>Here it is:</p>

<div class="language-javascript highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kd">function</span> <span class="nf">goodOnes</span><span class="p">(</span><span class="nx">items</span><span class="p">)</span> <span class="p">{</span>
  <span class="k">return</span> <span class="nx">R</span><span class="p">.</span><span class="nf">reduce</span><span class="p">(</span><span class="nx">theGoodOne</span><span class="p">,</span> <span class="p">[],</span> <span class="nx">items</span><span class="p">);</span>

  <span class="kd">function</span> <span class="nf">theGoodOne</span><span class="p">(</span><span class="nx">acc</span><span class="p">,</span> <span class="nx">item</span><span class="p">)</span> <span class="p">{</span>
    <span class="k">if </span><span class="p">(</span><span class="nx">item</span><span class="p">.</span><span class="nx">good</span><span class="p">)</span> <span class="p">{</span>
      <span class="k">return</span> <span class="nx">acc</span><span class="p">.</span><span class="nf">concat</span><span class="p">(</span><span class="nx">item</span><span class="p">.</span><span class="nx">id</span><span class="p">);</span>
    <span class="p">}</span> <span class="k">else</span> <span class="k">if </span><span class="p">(</span><span class="nx">item</span><span class="p">.</span><span class="nx">children</span> <span class="o">&amp;&amp;</span> <span class="nx">item</span><span class="p">.</span><span class="nx">children</span><span class="p">.</span><span class="nx">length</span> <span class="o">&gt;</span> <span class="mi">0</span><span class="p">)</span> <span class="p">{</span>
      <span class="k">return</span> <span class="nx">R</span><span class="p">.</span><span class="nf">reduce</span><span class="p">(</span><span class="nx">theGoodOne</span><span class="p">,</span> <span class="nx">acc</span><span class="p">,</span> <span class="nx">item</span><span class="p">.</span><span class="nx">children</span><span class="p">);</span>
    <span class="p">}</span>
    <span class="k">return</span> <span class="nx">acc</span><span class="p">;</span>
  <span class="p">}</span>
<span class="p">}</span>
</code></pre></div></div>

<p>As a side note, you don’t really have to use Ramda.js.
<code class="language-plaintext highlighter-rouge">Array.prototype.reduce</code> does the same, although in a less elegant way.</p>

<h3 id="explanation">Explanation</h3>

<p>What this function does is basically just <strong>collecting values</strong>. The
starting point is an empty array, you can see that as the second
argument in the first line. <code class="language-plaintext highlighter-rouge">theGoodOne</code> is another function (a closure,
to be specific) that is implicitly taking two arguments: <code class="language-plaintext highlighter-rouge">acc</code> (the
<em>accumulator</em>, the empty array) and <code class="language-plaintext highlighter-rouge">item</code> (the current item in the loop).</p>

<p>If the item is good, we return a <strong>new array</strong> with the item’s ID.
Otherwise, we return the accumulator. However, if the item happens to
have some children, we start over doing the same thing (i.e. looping
over its children), also keeping track of the accumulator we already
have this time. It might be still empty, but we don’t care yet. We just
return it at the very end.</p>

<p>Now, you might have noticed a bug: what happens if the item is good, but also
has children? … Yes, that item will be discarded! I did it on purpose
by the way. When I made this function, the original array of items never
had any good item <em>with</em> children. Only good items, or items with children.
The algorithm is reflecting this, so it’s technically not a bug.</p>

<p>If you’re curious about what’s the original intent behind this function, it is to
collect values from an <strong>infinitely nestable architecture of UI components</strong>.
There are <em>text</em> components, <em>number</em> components, <em>datepickers</em> etc…
those are all part of a category called <em>fields</em>. There are also
<em>wrappers</em>, that could be for example a <em>fieldset</em> or a <em>grid</em>. Wrappers can
contain fields, but also other wrappers.</p>

<p>So what if you have such data structure with so many components and all
you need is just an array of fields? Simple, just <strong>reduce recursively</strong>
on it! ;)</p>

<p>More in general, you can use the <strong>recursive reduce</strong> whenever you have
a nested data structure (such as an array of arrays) and you want to get something out of it.</p>

<h2 id="solution-in-clojure">Solution in Clojure</h2>

<p>This <strong>recursive solution</strong> follows the same logic as the JavaScript
one, but somehow it feels superior. It could probably be rewritten in a
more elegant way I guess, but I’m not very experienced with Clojure so
here we go:</p>

<div class="language-clojure highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="p">(</span><span class="k">defn</span><span class="w"> </span><span class="n">good-one</span><span class="w"> </span><span class="p">[</span><span class="n">acc</span><span class="w"> </span><span class="n">item</span><span class="p">]</span><span class="w">
  </span><span class="p">(</span><span class="k">if</span><span class="w"> </span><span class="p">(</span><span class="nf">item</span><span class="w"> </span><span class="no">:good</span><span class="p">)</span><span class="w">
    </span><span class="p">(</span><span class="nb">conj</span><span class="w"> </span><span class="n">acc</span><span class="w"> </span><span class="p">(</span><span class="nf">item</span><span class="w"> </span><span class="no">:id</span><span class="p">))</span><span class="w">
    </span><span class="p">(</span><span class="k">if</span><span class="w"> </span><span class="p">(</span><span class="nb">seq</span><span class="w"> </span><span class="p">(</span><span class="nf">item</span><span class="w"> </span><span class="no">:children</span><span class="p">))</span><span class="w">
      </span><span class="p">(</span><span class="nb">reduce</span><span class="w"> </span><span class="n">good-one</span><span class="w"> </span><span class="n">acc</span><span class="w"> </span><span class="p">(</span><span class="nf">item</span><span class="w"> </span><span class="no">:children</span><span class="p">))</span><span class="w">
      </span><span class="n">acc</span><span class="p">)))</span><span class="w">

</span><span class="p">(</span><span class="k">defn</span><span class="w"> </span><span class="n">good-ones</span><span class="w"> </span><span class="p">[</span><span class="n">collection</span><span class="p">]</span><span class="w">
  </span><span class="p">(</span><span class="nb">reduce</span><span class="w"> </span><span class="n">good-one</span><span class="w"> </span><span class="p">[]</span><span class="w"> </span><span class="n">collection</span><span class="p">))</span><span class="w">
</span></code></pre></div></div>

<h2 id="demo--download">Demo &amp; Download</h2>

<p>Everything is on GitHub if you want to fiddle around – just follow the instructions to get the demos up and running on your computer.</p>

<ul>
  <li>JavaScript <a href="https://github.com/simonewebdesign/es2015-recursive-reduce/blob/master/main.js">GitHub source</a> - <a href="https://github.com/simonewebdesign/es2015-recursive-reduce#readme">Readme instructions</a></li>
  <li>Clojure <a href="https://github.com/simonewebdesign/clojure-recursive-reduce/blob/master/test/clojure_recursive_reduce/core_test.clj">GitHub source</a> - <a href="https://github.com/simonewebdesign/clojure-recursive-reduce#readme">Readme instructions</a></li>
</ul>
]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[Blending together two lists in Elm and Swift]]></title>
    <link href="https://simonewebdesign.it/blend-together-two-lists-in-elm-and-swift/"/>
    <updated>2016-07-03T19:30:00+00:00</updated>
    <id>https://simonewebdesign.it/blend-together-two-lists-in-elm-and-swift</id>
    <content type="html"><![CDATA[<p>Here’s a fun kata:</p>

<blockquote>
  <p>Create a <code class="language-plaintext highlighter-rouge">blend</code> function that, given two lists of the same length, returns a new list with each element alternated. E.g.:</p>

  <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>blend [1, 2, 3] [4, 5, 6]
=&gt; [1, 4, 2, 5, 3, 6]
</code></pre></div>  </div>
</blockquote>

<p>As with all challenges, it can be solved in many different ways. However this particular one is easily solvable with functional programming techniques such as recursion.</p>

<p>You can try implementing it on your own first or just look straight at the solutions below.</p>

<h2 id="solution-in-elm">Solution in Elm</h2>

<p>The one below is probably the most straightforward solution:</p>

<div class="language-haskell highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="n">blend</span> <span class="o">:</span> <span class="kt">List</span> <span class="n">a</span> <span class="o">-&gt;</span> <span class="kt">List</span> <span class="n">a</span> <span class="o">-&gt;</span> <span class="kt">List</span> <span class="n">a</span>
<span class="n">blend</span> <span class="n">xs</span> <span class="n">ys</span> <span class="o">=</span>
    <span class="kr">case</span> <span class="n">xs</span> <span class="kr">of</span>
        <span class="n">x</span> <span class="o">::</span> <span class="n">xs'</span> <span class="o">-&gt;</span> <span class="n">x</span> <span class="o">::</span> <span class="n">blend</span> <span class="n">ys</span> <span class="n">xs'</span>
        <span class="kr">_</span> <span class="o">-&gt;</span> <span class="kt">[]</span>
</code></pre></div></div>

<p>Notice how I exchanged the arguments in the recursion call. That did the trick!</p>

<p>Let’s try it in the REPL – I added slashes so you can copy-paste the function:</p>

<div class="language-haskell highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="o">$</span> <span class="n">elm</span><span class="o">-</span><span class="n">repl</span>

<span class="o">&gt;</span> <span class="n">blend</span> <span class="n">xs</span> <span class="n">ys</span> <span class="o">=</span> <span class="nf">\</span>
    <span class="kr">case</span> <span class="n">xs</span> <span class="kr">of</span> <span class="nf">\</span>
        <span class="n">x</span> <span class="o">::</span> <span class="n">xs'</span> <span class="o">-&gt;</span> <span class="n">x</span> <span class="o">::</span> <span class="n">blend</span> <span class="n">ys</span> <span class="n">xs'</span> <span class="nf">\</span>
        <span class="kr">_</span> <span class="o">-&gt;</span> <span class="kt">[]</span>

<span class="o">&lt;</span><span class="n">function</span><span class="o">&gt;</span> <span class="o">:</span> <span class="kt">List</span> <span class="n">a</span> <span class="o">-&gt;</span> <span class="kt">List</span> <span class="n">a</span> <span class="o">-&gt;</span> <span class="kt">List</span> <span class="n">a</span>

<span class="o">&gt;</span> <span class="n">blend</span> <span class="p">[</span><span class="mi">0</span><span class="p">,</span><span class="mi">0</span><span class="p">,</span><span class="mi">0</span><span class="p">]</span> <span class="p">[</span><span class="mi">1</span><span class="p">,</span><span class="mi">1</span><span class="p">,</span><span class="mi">1</span><span class="p">]</span>
<span class="p">[</span><span class="mi">0</span><span class="p">,</span><span class="mi">1</span><span class="p">,</span><span class="mi">0</span><span class="p">,</span><span class="mi">1</span><span class="p">,</span><span class="mi">0</span><span class="p">,</span><span class="mi">1</span><span class="p">]</span> <span class="o">:</span> <span class="kt">List</span> <span class="n">number</span>
</code></pre></div></div>

<h2 id="solution-in-swift">Solution in Swift</h2>

<p>We can achieve the same in Swift by using an extension that splits up an Array into head and tail (credits to <a href="http://chris.eidhof.nl/post/swift-tricks/">Chris Eidhof</a>):</p>

<div class="language-swift highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kd">extension</span> <span class="kt">Array</span> <span class="p">{</span>
    <span class="k">var</span> <span class="nv">match</span> <span class="p">:</span> <span class="p">(</span><span class="nv">head</span><span class="p">:</span> <span class="kt">T</span><span class="p">,</span> <span class="nv">tail</span><span class="p">:</span> <span class="p">[</span><span class="kt">T</span><span class="p">])?</span> <span class="p">{</span>
      <span class="nf">return</span> <span class="p">(</span><span class="n">count</span> <span class="o">&gt;</span> <span class="mi">0</span><span class="p">)</span> <span class="p">?</span> <span class="p">(</span><span class="k">self</span><span class="p">[</span><span class="mi">0</span><span class="p">],</span><span class="kt">Array</span><span class="p">(</span><span class="k">self</span><span class="p">[</span><span class="mi">1</span><span class="o">..&lt;</span><span class="n">count</span><span class="p">]))</span> <span class="p">:</span> <span class="kc">nil</span>
    <span class="p">}</span>
<span class="p">}</span>
</code></pre></div></div>

<p>And here’s the solution:</p>

<div class="language-swift highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kd">func</span> <span class="nf">blend</span><span class="p">(</span><span class="nv">firstArray</span><span class="p">:</span> <span class="kt">Array</span><span class="o">&lt;</span><span class="kt">AnyObject</span><span class="o">&gt;</span><span class="p">,</span> <span class="nv">secondArray</span><span class="p">:</span> <span class="kt">Array</span><span class="o">&lt;</span><span class="kt">AnyObject</span><span class="o">&gt;</span><span class="p">)</span> <span class="o">-&gt;</span> <span class="kt">Array</span><span class="o">&lt;</span><span class="kt">AnyObject</span><span class="o">&gt;</span> <span class="p">{</span>
    <span class="k">if</span> <span class="k">let</span> <span class="p">(</span><span class="nv">head</span><span class="p">,</span> <span class="nv">tail</span><span class="p">)</span> <span class="o">=</span> <span class="n">firstArray</span><span class="o">.</span><span class="n">match</span> <span class="p">{</span>
        <span class="k">return</span> <span class="p">[</span><span class="n">head</span><span class="p">]</span> <span class="o">+</span> <span class="nf">blend</span><span class="p">(</span><span class="n">secondArray</span><span class="p">,</span> <span class="nv">secondArray</span><span class="p">:</span> <span class="n">tail</span><span class="p">)</span>
    <span class="p">}</span> <span class="k">else</span> <span class="p">{</span>
        <span class="k">return</span> <span class="p">[]</span>
    <span class="p">}</span>
<span class="p">}</span>
</code></pre></div></div>

<p>If you know of a better way, please let me know! Also feel free to leave a comment with any other alternative solution, even in other languages.</p>
]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[How to get the AST of an Elixir program]]></title>
    <link href="https://simonewebdesign.it/how-to-get-the-ast-of-an-elixir-program/"/>
    <updated>2015-11-14T19:43:10+00:00</updated>
    <id>https://simonewebdesign.it/how-to-get-the-ast-of-an-elixir-program</id>
    <content type="html"><![CDATA[<p>Getting the <strong>AST</strong> (Abstract Syntax Tree) representation of an <strong>Elixir</strong> source is pretty simple.</p>

<p>Let’s say we want to get the <strong>AST of this file</strong>:</p>

<div class="language-elixir highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="c1"># lib/hello.ex</span>
<span class="k">defmodule</span> <span class="no">Hello</span> <span class="k">do</span>
  <span class="k">def</span> <span class="n">hi</span><span class="p">(</span><span class="n">name</span><span class="p">)</span> <span class="k">do</span>
    <span class="no">IO</span><span class="o">.</span><span class="n">puts</span> <span class="s2">"Hello "</span> <span class="o">&lt;&gt;</span> <span class="n">name</span>
  <span class="k">end</span>
<span class="k">end</span>
</code></pre></div></div>

<p>We can do it right away from <code class="language-plaintext highlighter-rouge">iex</code>:</p>

<div class="language-elixir highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="err">$</span> <span class="n">iex</span>
<span class="no">Erlang</span><span class="o">/</span><span class="no">OTP</span> <span class="mi">18</span> <span class="p">[</span><span class="n">erts</span><span class="o">-</span><span class="mf">7.0</span><span class="p">]</span> <span class="p">[</span><span class="n">source</span><span class="p">]</span> <span class="p">[</span><span class="mi">64</span><span class="o">-</span><span class="n">bit</span><span class="p">]</span> <span class="p">[</span><span class="ss">smp:</span><span class="mi">8</span><span class="p">:</span><span class="mi">8</span><span class="p">]</span> <span class="p">[</span><span class="n">async</span><span class="o">-</span><span class="ss">threads:</span><span class="mi">10</span><span class="p">]</span> <span class="p">[</span><span class="n">kernel</span><span class="o">-</span><span class="ss">poll:</span><span class="no">false</span><span class="p">]</span>

<span class="no">Interactive</span> <span class="no">Elixir</span> <span class="p">(</span><span class="mf">1.0</span><span class="o">.</span><span class="mi">5</span><span class="p">)</span> <span class="o">-</span> <span class="n">press</span> <span class="no">Ctrl</span><span class="o">+</span><span class="no">C</span> <span class="n">to</span> <span class="k">exit</span> <span class="p">(</span><span class="n">type</span> <span class="n">h</span><span class="p">()</span> <span class="no">ENTER</span> <span class="n">for</span> <span class="n">help</span><span class="p">)</span>
<span class="n">iex</span><span class="p">(</span><span class="mi">1</span><span class="p">)</span><span class="o">&gt;</span> <span class="p">{</span><span class="ss">:ok</span><span class="p">,</span> <span class="n">ast</span><span class="p">}</span> <span class="o">=</span> <span class="no">Code</span><span class="o">.</span><span class="n">string_to_quoted</span><span class="p">(</span><span class="no">File</span><span class="o">.</span><span class="n">read!</span><span class="p">(</span><span class="s2">"lib/hello.ex"</span><span class="p">))</span>
<span class="p">{</span><span class="ss">:ok</span><span class="p">,</span>
 <span class="p">{</span><span class="ss">:defmodule</span><span class="p">,</span> <span class="p">[</span><span class="ss">line:</span> <span class="mi">1</span><span class="p">],</span>
  <span class="p">[{</span><span class="ss">:__aliases__</span><span class="p">,</span> <span class="p">[</span><span class="ss">counter:</span> <span class="mi">0</span><span class="p">,</span> <span class="ss">line:</span> <span class="mi">1</span><span class="p">],</span> <span class="p">[</span><span class="ss">:Hello</span><span class="p">]},</span>
   <span class="p">[</span><span class="k">do</span><span class="p">:</span> <span class="p">{</span><span class="ss">:def</span><span class="p">,</span> <span class="p">[</span><span class="ss">line:</span> <span class="mi">3</span><span class="p">],</span>
     <span class="p">[{</span><span class="ss">:hi</span><span class="p">,</span> <span class="p">[</span><span class="ss">line:</span> <span class="mi">3</span><span class="p">],</span> <span class="p">[{</span><span class="ss">:name</span><span class="p">,</span> <span class="p">[</span><span class="ss">line:</span> <span class="mi">3</span><span class="p">],</span> <span class="no">nil</span><span class="p">}]},</span>
      <span class="p">[</span><span class="k">do</span><span class="p">:</span> <span class="p">{{:</span><span class="o">.</span><span class="p">,</span> <span class="p">[</span><span class="ss">line:</span> <span class="mi">4</span><span class="p">],</span>
         <span class="p">[{</span><span class="ss">:__aliases__</span><span class="p">,</span> <span class="p">[</span><span class="ss">counter:</span> <span class="mi">0</span><span class="p">,</span> <span class="ss">line:</span> <span class="mi">4</span><span class="p">],</span> <span class="p">[</span><span class="ss">:IO</span><span class="p">]},</span> <span class="ss">:puts</span><span class="p">]},</span> <span class="p">[</span><span class="ss">line:</span> <span class="mi">4</span><span class="p">],</span>
        <span class="p">[{</span><span class="ss">:&lt;&gt;</span><span class="p">,</span> <span class="p">[</span><span class="ss">line:</span> <span class="mi">4</span><span class="p">],</span> <span class="p">[</span><span class="s2">"Hello "</span><span class="p">,</span> <span class="p">{</span><span class="ss">:name</span><span class="p">,</span> <span class="p">[</span><span class="ss">line:</span> <span class="mi">4</span><span class="p">],</span> <span class="no">nil</span><span class="p">}]}]}]]}]]}}</span>
</code></pre></div></div>

<p>In our case, the <code class="language-plaintext highlighter-rouge">ast</code> variable will contain the full AST of the source code.</p>

<p>In case you want to get the <strong>AST of a single line</strong>, it’s even simpler:</p>

<div class="language-elixir highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="n">iex</span><span class="p">(</span><span class="mi">1</span><span class="p">)</span><span class="o">&gt;</span> <span class="n">name</span> <span class="o">=</span> <span class="s2">"John"</span>
<span class="s2">"John"</span>

<span class="n">iex</span><span class="p">(</span><span class="mi">2</span><span class="p">)</span><span class="o">&gt;</span> <span class="no">IO</span><span class="o">.</span><span class="n">puts</span> <span class="s2">"Hello "</span> <span class="o">&lt;&gt;</span> <span class="n">name</span>
<span class="no">Hello</span> <span class="no">John</span>
<span class="ss">:ok</span>

<span class="n">iex</span><span class="p">(</span><span class="mi">3</span><span class="p">)</span><span class="o">&gt;</span> <span class="n">ast</span> <span class="o">=</span> <span class="kn">quote</span> <span class="k">do</span><span class="p">:</span> <span class="no">IO</span><span class="o">.</span><span class="n">puts</span> <span class="s2">"Hello "</span> <span class="o">&lt;&gt;</span> <span class="n">name</span>
<span class="p">{{:</span><span class="o">.</span><span class="p">,</span> <span class="p">[],</span> <span class="p">[{</span><span class="ss">:__aliases__</span><span class="p">,</span> <span class="p">[</span><span class="ss">alias:</span> <span class="no">false</span><span class="p">],</span> <span class="p">[</span><span class="ss">:IO</span><span class="p">]},</span> <span class="ss">:puts</span><span class="p">]},</span> <span class="p">[],</span>
 <span class="p">[{</span><span class="ss">:&lt;&gt;</span><span class="p">,</span> <span class="p">[</span><span class="ss">context:</span> <span class="no">Elixir</span><span class="p">,</span> <span class="kn">import</span><span class="p">:</span> <span class="no">Kernel</span><span class="p">],</span> <span class="p">[</span><span class="s2">"Hello "</span><span class="p">,</span> <span class="p">{</span><span class="ss">:name</span><span class="p">,</span> <span class="p">[],</span> <span class="no">Elixir</span><span class="p">}]}]}</span>
</code></pre></div></div>

<p>For more context, I recommend reading the <a href="https://elixir-lang.org/getting-started/meta/quote-and-unquote.html">introduction to meta-programming in Elixir</a> on Elixir’s official site.</p>

<p>In case you’re interested in <strong>parsing Elixir</strong>, <a href="https://andrealeopardi.com/posts/tokenizing-and-parsing-in-elixir-using-leex-and-yecc/">Tokenizing and parsing in Elixir with yecc and leex</a> by Andrea Leopardi is a very recommended reading.</p>

<p>Have fun with Elixir!</p>
]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[How To Get Environment Variables in the Browser]]></title>
    <link href="https://simonewebdesign.it/how-to-get-environment-variables-in-the-browser/"/>
    <updated>2015-08-03T11:00:00+00:00</updated>
    <id>https://simonewebdesign.it/how-to-get-environment-variables-in-the-browser</id>
    <content type="html"><![CDATA[<h2 id="preface-why">Preface: Why?</h2>

<p><strong>Environment variables</strong> are very useful for <strong>configuring your app</strong> depending on the environment, without having to hardcode any value in the source.</p>

<p>At my current company we are building a <strong>microservice infrastructure</strong>, where the <strong>frontend</strong> and the <strong>backend</strong> are completely decoupled applications. We also use <a href="https://docker.com/">Docker</a> to manage these microservices and link them together. Turns out that storing the configuration in the environment—as opposed to storing it in the database or in the code itself—is quite valuable, as described also in the <a href="http://12factor.net/config">twelve-factor</a> methodology.</p>

<h3 id="advantages">Advantages:</h3>

<ul>
  <li>Language and OS agnostic;</li>
  <li>Easy to change between deploys without changing any code;</li>
  <li>Impossible to accidentally check in source control.</li>
</ul>

<h2 id="how">How?</h2>

<p>A web page doesn’t have access to OS variables, so you can’t normally use them.</p>

<p>The solution is pretty simple: you just need to <strong>generate a file that contains them</strong>.</p>

<p>For such a trivial task you could be tempted to use your language of choice, e.g. in JavaScript (Node.js) you have access to <code class="language-plaintext highlighter-rouge">process.env.SOME_VAR</code>. In Python you would probably do <code class="language-plaintext highlighter-rouge">os.getenv('SOME_VAR')</code> and in Ruby you’d use <code class="language-plaintext highlighter-rouge">ENV['SOME_VAR']</code>—but what about some old-school shell scripting? The script could be as simple as:</p>

<div class="language-bash highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="c"># bin/env.sh</span>
<span class="nb">echo</span> <span class="s2">"env = {"</span>
<span class="nb">echo</span> <span class="s2">"  USER: '</span><span class="nv">$USER</span><span class="s2">',"</span>
<span class="nb">echo</span> <span class="s2">"  HOSTNAME: '</span><span class="nv">$HOSTNAME</span><span class="s2">'"</span>
<span class="nb">echo</span> <span class="s2">"}"</span>
</code></pre></div></div>

<p>That, when executed, will become:</p>

<div class="language-javascript highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="c1">// env.js</span>
<span class="nx">env</span> <span class="o">=</span> <span class="p">{</span>
  <span class="na">USER</span><span class="p">:</span> <span class="dl">'</span><span class="s1">yourname</span><span class="dl">'</span><span class="p">,</span>
  <span class="na">HOSTNAME</span><span class="p">:</span> <span class="dl">'</span><span class="s1">ubuntu</span><span class="dl">'</span>
<span class="p">}</span>
</code></pre></div></div>

<p>And the script to execute on the shell is:</p>

<div class="language-bash highlighter-rouge"><div class="highlight"><pre class="highlight"><code>./bin/env.sh <span class="o">&gt;</span> env.js
</code></pre></div></div>

<p>Pretty straightforward, isn’t it?</p>

<h3 id="test-it">Test it:</h3>

<div class="language-html highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="cp">&lt;!DOCTYPE html&gt;</span>
<span class="nt">&lt;html&gt;</span>
<span class="nt">&lt;head&gt;</span>
  ...
<span class="nt">&lt;/head&gt;</span>
<span class="nt">&lt;body&gt;</span>
  <span class="nt">&lt;script </span><span class="na">src=</span><span class="s">"env.js"</span><span class="nt">&gt;&lt;/script&gt;</span>
  <span class="nt">&lt;script&gt;</span>
    <span class="nx">console</span><span class="p">.</span><span class="nf">log</span><span class="p">(</span><span class="nx">env</span><span class="p">.</span><span class="nx">USER</span><span class="p">,</span> <span class="nx">env</span><span class="p">.</span><span class="nx">HOSTNAME</span><span class="p">);</span>
  <span class="nt">&lt;/script&gt;</span>
<span class="nt">&lt;/body&gt;</span>
<span class="nt">&lt;/html&gt;</span>
</code></pre></div></div>

<p>One downside to this approach is that you have to “make a build” every time you change the variables. If you know any workarounds or better solutions, please let me know!</p>

<h3 id="source-and-download">Source and download</h3>

<p>Find the source code on <a href="https://github.com/simonewebdesign/frontend-env-vars">GitHub</a>. Download the zip file <a href="https://github.com/simonewebdesign/frontend-env-vars/archive/master.zip">here</a>.</p>

<p>Have fun!</p>
]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[Making a game from scratch in HTML5]]></title>
    <link href="https://simonewebdesign.it/making-a-game-from-scratch-in-html5/"/>
    <updated>2014-12-01T16:06:53+00:00</updated>
    <id>https://simonewebdesign.it/making-a-game-from-scratch-in-html5</id>
    <content type="html"><![CDATA[<blockquote>
  <p>“Pong is one of the earliest arcade video games; it is a tennis sports game featuring simple two-dimensional graphics.” - Wikipedia</p>
</blockquote>

<p>Have you ever dreamed of building a game in JavaScript? I did, and I also managed to make my first one. Of course I also wrote some tips and gotchas to help you complete this nice challenge.</p>

<h2 id="how-to-make-pong-in-html5-canvas">How to make Pong in HTML5 canvas</h2>

<p>Pong, at it’s core, is an extremely simple game. That’s why it’s a good one to begin with if you have just started learning game design basics. Of course you could start with <a href="//www.gamefromscratch.com/post/2013/08/01/Just-starting-out-what-games-should-I-make.aspx" rel="external">many other games</a>, but if you are looking for something relatively simple to build, Pong really is one of the simplest games ever made.</p>

<p><abbr title="As far as I know">AFAIK</abbr>, there are at least two ways of doing it: I personally call them the <em>“simple way”</em> and the <em>“hard way”</em>. I did both, but first let’s explore the simple one.</p>

<h3 id="project-structure">Project structure</h3>

<p>I aimed to make it as simple as possible, so I just created one HTML file that is referencing few JavaScript files. You may ask, why not a whole single file? Because it’s usually preferable to have many little files rather than one massive plate of spaghetti code. So here’s served the project’s structure:</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>index.html
canvas.js
game.js
keyboard.js
main.js
render.js
reset.js
update.js
</code></pre></div></div>

<p><strong>index.html</strong> is our single entry point to the game.</p>

<p><strong>canvas.js</strong> contains the code for initializing the <code class="language-plaintext highlighter-rouge">canvas</code> <abbr title="Document Object Model">DOM</abbr> object and the 2D context.</p>

<p><strong>game.js</strong> contains the game objects. This file will be executed only once at the beginning, when the game loads.</p>

<p><strong>keyboard.js</strong> has the keyboard bindings.</p>

<p><strong>main.js</strong> is perhaps the most important file, because it contains the main game loop.</p>

<p><strong>render.js</strong> does… the rendering. (you don’t say?)</p>

<p><strong>reset.js</strong> is for resetting the game to the initial state, called every time a player wins.</p>

<p><strong>update.js</strong> contains 90% of the game logic, and obviously is for updating the game state (before rendering).</p>

<h3 id="the-main-loop">The main loop</h3>

<p>The main loop is at the core of our game. Maybe it’s hard to believe, but virtually every single videogame in the world lives and dies <a href="//designoidgames.com/2013/01/game-programming-basics-time/" rel="external">within a loop</a>.</p>

<p>Implementing a game loop is a lot simpler than you think, but it’s not the focus of this tutorial. The resource I highly recommend for getting started is <a href="http://www.lostdecadegames.com/how-to-make-a-simple-html5-canvas-game/">How to make a simple HTML5 Canvas game</a>, by Matt Hackett. All my work is actually based on his tutorial. Read it, and you’ll get a basic understanding of the fundamentals of game development.</p>

<p>We want to focus on the game logic now, so for the time being let’s pretend our game loop looks like this:</p>

<div class="language-javascript highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">while </span><span class="p">(</span><span class="kc">true</span><span class="p">)</span> <span class="p">{</span>
  <span class="nf">update</span><span class="p">();</span> <span class="c1">// update game objects</span>
  <span class="nf">render</span><span class="p">();</span> <span class="c1">// render game objects</span>
<span class="p">}</span>
</code></pre></div></div>

<p>Got it? :-)</p>

<h3 id="ball-movement">Ball movement</h3>

<p>How do we make the ball moving across the screen? In JavaScript, we can define objects with properties. The essential properties of our <code class="language-plaintext highlighter-rouge">ball</code> object are <code class="language-plaintext highlighter-rouge">position</code> and <code class="language-plaintext highlighter-rouge">speed</code>. The <code class="language-plaintext highlighter-rouge">position</code> represents the <em>coordinates</em> where the object is in the canvas space. Example:</p>

<div class="language-javascript highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kd">var</span> <span class="nx">ball</span> <span class="o">=</span> <span class="p">{</span>
  <span class="na">x</span><span class="p">:</span> <span class="mi">0</span><span class="p">,</span>
  <span class="na">y</span><span class="p">:</span> <span class="mi">0</span><span class="p">,</span>
  <span class="na">speedX</span><span class="p">:</span> <span class="mi">0</span><span class="p">,</span>
  <span class="na">speedY</span><span class="p">:</span> <span class="mi">0</span>
<span class="p">}</span>
</code></pre></div></div>

<p>In order to make it move, we should change its position, and we can do it through the speed. This is the heart of our game:</p>

<div class="language-javascript highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">if </span><span class="p">(</span><span class="nx">isGameStarted</span><span class="p">)</span> <span class="p">{</span>
  <span class="c1">// Ball movement</span>
  <span class="nx">ball</span><span class="p">.</span><span class="nx">x</span> <span class="o">+=</span> <span class="nx">ball</span><span class="p">.</span><span class="nx">speedX</span> <span class="o">*</span> <span class="nx">modifier</span><span class="p">;</span>
  <span class="nx">ball</span><span class="p">.</span><span class="nx">y</span> <span class="o">+=</span> <span class="nx">ball</span><span class="p">.</span><span class="nx">speedY</span> <span class="o">*</span> <span class="nx">modifier</span><span class="p">;</span>
<span class="p">}</span>
</code></pre></div></div>

<p>As you can imagine, <code class="language-plaintext highlighter-rouge">isGameStarted</code> is just a boolean flag. But what’s <code class="language-plaintext highlighter-rouge">modifier</code>? Well, it’s the <strong>delta time</strong> of our game loop. Put simply, the <a href="//en.wikipedia.org/wiki/Delta_timing" rel="external">delta time</a> is the time elapsed between a frame and another. This is very useful because we can use it to calculate how fast the ball should move. Without it, the game would just lag all the time.</p>

<h3 id="ball-bounce">Ball bounce</h3>

<p>The game logic is mainly about the ball: it should be able to bounce away from the paddles. How can you implement that? It’s pretty simple - have a look at the code below.</p>

<div class="language-javascript highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="c1">// Ball is out of the left boundary</span>
<span class="k">if </span><span class="p">(</span><span class="nx">ball</span><span class="p">.</span><span class="nx">x</span> <span class="o">&lt;=</span> <span class="mi">0</span><span class="p">)</span> <span class="p">{</span>
  <span class="c1">// Player 2 wins!</span>
  <span class="nx">p2</span><span class="p">.</span><span class="nx">score</span><span class="o">++</span><span class="p">;</span>
  <span class="nf">reset</span><span class="p">();</span> <span class="c1">// reset the game to the initial state</span>
<span class="p">}</span>

<span class="c1">// Ball is out of the right boundary</span>
<span class="k">if </span><span class="p">(</span><span class="nx">ball</span><span class="p">.</span><span class="nx">x</span> <span class="o">&gt;=</span> <span class="nx">canvas</span><span class="p">.</span><span class="nx">width</span> <span class="o">-</span> <span class="nx">ball</span><span class="p">.</span><span class="nx">size</span><span class="p">)</span> <span class="p">{</span>
  <span class="c1">// Player 1 wins!</span>
  <span class="nx">p1</span><span class="p">.</span><span class="nx">score</span><span class="o">++</span><span class="p">;</span>
  <span class="nf">reset</span><span class="p">();</span>
<span class="p">}</span>

<span class="c1">// Ball is colliding with the top</span>
<span class="k">if </span><span class="p">(</span><span class="nx">ball</span><span class="p">.</span><span class="nx">y</span> <span class="o">&lt;=</span> <span class="mi">0</span><span class="p">)</span> <span class="p">{</span>
  <span class="nx">ball</span><span class="p">.</span><span class="nx">speedY</span> <span class="o">=</span> <span class="nb">Math</span><span class="p">.</span><span class="nf">abs</span><span class="p">(</span><span class="nx">ball</span><span class="p">.</span><span class="nx">speedY</span><span class="p">);</span>
<span class="p">}</span>

<span class="c1">// Ball is colliding with the bottom</span>
<span class="k">if </span><span class="p">(</span><span class="nx">ball</span><span class="p">.</span><span class="nx">y</span> <span class="o">+</span> <span class="nx">ball</span><span class="p">.</span><span class="nx">size</span> <span class="o">&gt;=</span> <span class="nx">canvas</span><span class="p">.</span><span class="nx">height</span><span class="p">)</span> <span class="p">{</span>
  <span class="nx">ball</span><span class="p">.</span><span class="nx">speedY</span> <span class="o">=</span> <span class="nb">Math</span><span class="p">.</span><span class="nf">abs</span><span class="p">(</span><span class="nx">ball</span><span class="p">.</span><span class="nx">speedY</span><span class="p">)</span> <span class="o">*</span> <span class="o">-</span><span class="mi">1</span><span class="p">;</span> <span class="c1">// inverted</span>
<span class="p">}</span>
</code></pre></div></div>

<p>Can you see what’s going on in the code? Basically, if the ball goes beyond the canvas’ left or right boundaries, all we do is <strong>increment the score and reset the game</strong>. If the ball touches the top or the bottom instead, we <strong>invert its speed on the Y axis</strong>. If you think about it, it’s all you need to make something reflect over a surface. So, in other words, if the speed is negative we make it positive, and viceversa.</p>

<h3 id="collision-detection">Collision detection</h3>

<p>What should happen when the ball touches one of the paddles? Fundamentally the same thing explained above: it should bounce away, reflecting on the paddle’s surface (and to do this we invert the Y speed). But how do we actually check if they are <strong>colliding</strong>?</p>

<p>The most common kind of collision detection is called <strong>AABB - Axis-Aligned Bounding Boxes</strong>. You can find plenty of resources around the Web explaining how this technique works, so I won’t talk about it (have a quick search for <em>“AABB collision detection”</em>, or just keep reading). As <a href="http://en.wikipedia.org/wiki/Linus_Torvalds" rel="external">Linus Torvalds</a> once said,</p>

<blockquote>
  <p>“Talk is cheap. Show me the code.”</p>
</blockquote>

<p>Here we go:</p>

<div class="language-javascript highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">if </span><span class="p">(</span>
  <span class="nx">ball</span><span class="p">.</span><span class="nx">x</span> <span class="o">&lt;=</span> <span class="p">(</span><span class="nx">p1</span><span class="p">.</span><span class="nx">x</span> <span class="o">+</span> <span class="nx">p1</span><span class="p">.</span><span class="nx">width</span><span class="p">)</span>
  <span class="o">&amp;&amp;</span> <span class="nx">p1</span><span class="p">.</span><span class="nx">x</span> <span class="o">&lt;=</span> <span class="p">(</span><span class="nx">ball</span><span class="p">.</span><span class="nx">x</span> <span class="o">+</span> <span class="nx">ball</span><span class="p">.</span><span class="nx">size</span><span class="p">)</span>
  <span class="o">&amp;&amp;</span> <span class="nx">ball</span><span class="p">.</span><span class="nx">y</span> <span class="o">&lt;=</span> <span class="p">(</span><span class="nx">p1</span><span class="p">.</span><span class="nx">y</span> <span class="o">+</span> <span class="nx">p1</span><span class="p">.</span><span class="nx">height</span><span class="p">)</span>
  <span class="o">&amp;&amp;</span> <span class="nx">p1</span><span class="p">.</span><span class="nx">y</span> <span class="o">&lt;=</span> <span class="p">(</span><span class="nx">ball</span><span class="p">.</span><span class="nx">y</span> <span class="o">+</span> <span class="nx">ball</span><span class="p">.</span><span class="nx">size</span><span class="p">)</span>
<span class="p">)</span> <span class="p">{</span>
  <span class="c1">// Ball is colliding with the left paddle</span>
  <span class="c1">// Ensure the speed on the X axis is positive</span>
  <span class="nx">ball</span><span class="p">.</span><span class="nx">speedX</span> <span class="o">=</span> <span class="nb">Math</span><span class="p">.</span><span class="nf">abs</span><span class="p">(</span><span class="nx">ball</span><span class="p">.</span><span class="nx">speedX</span><span class="p">);</span>

  <span class="c1">// Give the ball a bit of randomness by</span>
  <span class="c1">// increasing/decreasing its speed on the Y axis</span>
  <span class="nx">ball</span><span class="p">.</span><span class="nx">speedY</span> <span class="o">=</span> <span class="nf">randomize</span><span class="p">();</span>
<span class="p">}</span>
</code></pre></div></div>

<p>The logic for the right paddle is exactly the same, but the speed on the X axis should be negative instead. In my case I also added a <code class="language-plaintext highlighter-rouge">randomize()</code> function, so the game will be more interesting - you don’t have to implement it this way, but a bit of randomness never hurts in gaming!</p>

<div class="language-javascript highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kd">function</span> <span class="nf">randomize</span><span class="p">()</span> <span class="p">{</span>
  <span class="c1">// Random float between 0 and 999.9</span>
  <span class="kd">var</span> <span class="nx">_rand</span> <span class="o">=</span> <span class="nb">Math</span><span class="p">.</span><span class="nf">random</span><span class="p">()</span> <span class="o">*</span> <span class="mi">1000</span><span class="p">;</span>
  <span class="c1">// positive or negative?</span>
  <span class="k">return</span> <span class="nb">Math</span><span class="p">.</span><span class="nf">random</span><span class="p">()</span> <span class="o">&gt;</span> <span class="mf">0.5</span> <span class="p">?</span> <span class="nx">_rand</span> <span class="p">:</span> <span class="nx">_rand</span> <span class="o">*</span> <span class="o">-</span><span class="mi">1</span><span class="p">;</span>
<span class="p">}</span>
</code></pre></div></div>

<h3 id="paddle-movement">Paddle movement</h3>

<p>We move the paddles with the keyboard. Keyboard controls can be handled simply by keeping track of which key is currently being pressed (watch for the <code class="language-plaintext highlighter-rouge">keydown</code> event). We can use a simple JavaScript object for that (or an array if you prefer):</p>

<div class="language-javascript highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="c1">// Handle keyboard controls</span>
<span class="kd">var</span> <span class="nx">keysDown</span> <span class="o">=</span> <span class="p">{};</span>

<span class="nf">addEventListener</span><span class="p">(</span><span class="dl">"</span><span class="s2">keydown</span><span class="dl">"</span><span class="p">,</span> <span class="nf">function </span><span class="p">(</span><span class="nx">e</span><span class="p">)</span> <span class="p">{</span>
  <span class="nx">keysDown</span><span class="p">[</span><span class="nx">e</span><span class="p">.</span><span class="nx">keyCode</span><span class="p">]</span> <span class="o">=</span> <span class="kc">true</span><span class="p">;</span>
<span class="p">},</span> <span class="kc">false</span><span class="p">);</span>

<span class="nf">addEventListener</span><span class="p">(</span><span class="dl">"</span><span class="s2">keyup</span><span class="dl">"</span><span class="p">,</span> <span class="nf">function </span><span class="p">(</span><span class="nx">e</span><span class="p">)</span> <span class="p">{</span>
  <span class="k">delete</span> <span class="nx">keysDown</span><span class="p">[</span><span class="nx">e</span><span class="p">.</span><span class="nx">keyCode</span><span class="p">];</span>
<span class="p">},</span> <span class="kc">false</span><span class="p">);</span>
</code></pre></div></div>

<p>The <code class="language-plaintext highlighter-rouge">keyup</code> and <code class="language-plaintext highlighter-rouge">keydown</code> events are the only two we need for handling the whole keyboard. So on <code class="language-plaintext highlighter-rouge">keydown</code> we add the key; on <code class="language-plaintext highlighter-rouge">keyup</code> we remove it. Simple.</p>

<p>Of course we are going to need JavaScript objects for the paddles as well. In my game I called them <code class="language-plaintext highlighter-rouge">p1</code> and <code class="language-plaintext highlighter-rouge">p2</code>, which can be interpreted as <em>players</em> too.</p>

<p>Here’s the code:</p>

<div class="language-javascript highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="c1">// Update game objects</span>
<span class="kd">var</span> <span class="nx">update</span> <span class="o">=</span> <span class="nf">function </span><span class="p">(</span><span class="nx">modifier</span><span class="p">)</span> <span class="p">{</span>
  <span class="k">if </span><span class="p">(</span><span class="mi">87</span> <span class="k">in</span> <span class="nx">keysDown</span><span class="p">)</span> <span class="p">{</span> <span class="c1">// P1 holding up (key: w)</span>
    <span class="nx">p1</span><span class="p">.</span><span class="nx">y</span> <span class="o">-=</span> <span class="nx">p1</span><span class="p">.</span><span class="nx">speed</span> <span class="o">*</span> <span class="nx">modifier</span><span class="p">;</span>
  <span class="p">}</span>

  <span class="k">if </span><span class="p">(</span><span class="mi">83</span> <span class="k">in</span> <span class="nx">keysDown</span><span class="p">)</span> <span class="p">{</span> <span class="c1">// P1 holding down (key: s)</span>
    <span class="nx">p1</span><span class="p">.</span><span class="nx">y</span> <span class="o">+=</span> <span class="nx">p1</span><span class="p">.</span><span class="nx">speed</span> <span class="o">*</span> <span class="nx">modifier</span><span class="p">;</span>
  <span class="p">}</span>

  <span class="k">if </span><span class="p">(</span><span class="mi">38</span> <span class="k">in</span> <span class="nx">keysDown</span><span class="p">)</span> <span class="p">{</span> <span class="c1">// P2 holding up (key: arrow up)</span>
    <span class="nx">p2</span><span class="p">.</span><span class="nx">y</span> <span class="o">-=</span> <span class="nx">p2</span><span class="p">.</span><span class="nx">speed</span> <span class="o">*</span> <span class="nx">modifier</span><span class="p">;</span>
  <span class="p">}</span>

  <span class="k">if </span><span class="p">(</span><span class="mi">40</span> <span class="k">in</span> <span class="nx">keysDown</span><span class="p">)</span> <span class="p">{</span> <span class="c1">// P2 holding down (key: arrow down)</span>
    <span class="nx">p2</span><span class="p">.</span><span class="nx">y</span> <span class="o">+=</span> <span class="nx">p2</span><span class="p">.</span><span class="nx">speed</span> <span class="o">*</span> <span class="nx">modifier</span><span class="p">;</span>
  <span class="p">}</span>
<span class="p">}</span>
</code></pre></div></div>

<h3 id="rendering-the-objects-in-the-canvas">Rendering the objects in the canvas</h3>

<p>Here’s the <code class="language-plaintext highlighter-rouge">render()</code> function, in all its glory:</p>

<div class="language-javascript highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kd">var</span> <span class="nx">render</span> <span class="o">=</span> <span class="nf">function </span><span class="p">()</span> <span class="p">{</span>
  <span class="nx">ctx</span><span class="p">.</span><span class="nx">fillStyle</span> <span class="o">=</span> <span class="dl">"</span><span class="s2">#0F0</span><span class="dl">"</span><span class="p">;</span> <span class="c1">// green</span>

  <span class="c1">// P1</span>
  <span class="nx">ctx</span><span class="p">.</span><span class="nf">fillRect</span><span class="p">(</span><span class="nx">p1</span><span class="p">.</span><span class="nx">x</span><span class="p">,</span> <span class="nx">p1</span><span class="p">.</span><span class="nx">y</span><span class="p">,</span> <span class="nx">p1</span><span class="p">.</span><span class="nx">width</span><span class="p">,</span> <span class="nx">p1</span><span class="p">.</span><span class="nx">height</span><span class="p">);</span>

  <span class="c1">// P2</span>
  <span class="nx">ctx</span><span class="p">.</span><span class="nf">fillRect</span><span class="p">(</span><span class="nx">p2</span><span class="p">.</span><span class="nx">x</span><span class="p">,</span> <span class="nx">p2</span><span class="p">.</span><span class="nx">y</span><span class="p">,</span> <span class="nx">p2</span><span class="p">.</span><span class="nx">width</span><span class="p">,</span> <span class="nx">p2</span><span class="p">.</span><span class="nx">height</span><span class="p">);</span>

  <span class="c1">// ball</span>
  <span class="nx">ctx</span><span class="p">.</span><span class="nf">fillRect</span><span class="p">(</span><span class="nx">ball</span><span class="p">.</span><span class="nx">x</span><span class="p">,</span> <span class="nx">ball</span><span class="p">.</span><span class="nx">y</span><span class="p">,</span> <span class="nx">ball</span><span class="p">.</span><span class="nx">size</span><span class="p">,</span> <span class="nx">ball</span><span class="p">.</span><span class="nx">size</span><span class="p">);</span>

  <span class="c1">// Text options</span>
  <span class="nx">ctx</span><span class="p">.</span><span class="nx">fillStyle</span> <span class="o">=</span> <span class="dl">"</span><span class="s2">rgb(250, 250, 250)</span><span class="dl">"</span><span class="p">;</span>
  <span class="nx">ctx</span><span class="p">.</span><span class="nx">font</span> <span class="o">=</span> <span class="dl">"</span><span class="s2">18px Helvetica</span><span class="dl">"</span><span class="p">;</span>
  <span class="nx">ctx</span><span class="p">.</span><span class="nx">textAlign</span> <span class="o">=</span> <span class="dl">"</span><span class="s2">left</span><span class="dl">"</span><span class="p">;</span>
  <span class="nx">ctx</span><span class="p">.</span><span class="nx">textBaseline</span> <span class="o">=</span> <span class="dl">"</span><span class="s2">top</span><span class="dl">"</span><span class="p">;</span>

  <span class="c1">// P1 Score</span>
  <span class="nx">ctx</span><span class="p">.</span><span class="nf">fillText</span><span class="p">(</span><span class="nx">p1</span><span class="p">.</span><span class="nx">score</span><span class="p">,</span> <span class="mi">32</span><span class="p">,</span> <span class="mi">32</span><span class="p">);</span>

  <span class="c1">// P2 Score</span>
  <span class="nx">ctx</span><span class="p">.</span><span class="nf">fillText</span><span class="p">(</span><span class="nx">p2</span><span class="p">.</span><span class="nx">score</span><span class="p">,</span> <span class="nx">canvas</span><span class="p">.</span><span class="nx">width</span> <span class="o">-</span> <span class="mi">32</span><span class="p">,</span> <span class="mi">32</span><span class="p">);</span>
<span class="p">};</span>
</code></pre></div></div>
<p>It’s probably worth mentioning that you can use <code class="language-plaintext highlighter-rouge">JSON.stringify()</code> to debug your objects directly in the canvas, e.g.:</p>

<div class="language-javascript highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="c1">// Debugging the ball object</span>
<span class="nx">ctx</span><span class="p">.</span><span class="nf">fillText</span><span class="p">(</span><span class="dl">"</span><span class="s2">ball: </span><span class="dl">"</span> <span class="o">+</span> <span class="nx">JSON</span><span class="p">.</span><span class="nf">stringify</span><span class="p">(</span><span class="nx">ball</span><span class="p">),</span> <span class="mi">0</span><span class="p">,</span> <span class="mi">0</span><span class="p">);</span>
</code></pre></div></div>

<p>However, I don’t recommend it. Just use whatever your browser is offering! If you are a web developer you surely know that there’s a built-in JavaScript console for debugging in your browser (if you don’t, search for <em>developer tools</em>).</p>

<h3 id="resetting-the-game">Resetting the game</h3>

<p>We need to reset the game every time a player scores. The logic is very simple, we just need to provide default values for our objects. Example below.</p>

<div class="language-javascript highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="c1">// Reset the game</span>
<span class="kd">var</span> <span class="nx">reset</span> <span class="o">=</span> <span class="nf">function </span><span class="p">()</span> <span class="p">{</span>
  <span class="nx">isGameStarted</span> <span class="o">=</span> <span class="kc">false</span><span class="p">;</span>

  <span class="nx">ball</span><span class="p">.</span><span class="nx">x</span> <span class="o">=</span> <span class="p">(</span><span class="nx">canvas</span><span class="p">.</span><span class="nx">width</span> <span class="o">-</span> <span class="nx">ball</span><span class="p">.</span><span class="nx">size</span><span class="p">)</span> <span class="o">/</span> <span class="mi">2</span><span class="p">;</span>
  <span class="nx">ball</span><span class="p">.</span><span class="nx">y</span> <span class="o">=</span> <span class="p">(</span><span class="nx">canvas</span><span class="p">.</span><span class="nx">height</span> <span class="o">-</span> <span class="nx">ball</span><span class="p">.</span><span class="nx">size</span><span class="p">)</span> <span class="o">/</span> <span class="mi">2</span><span class="p">;</span>

  <span class="nx">ball</span><span class="p">.</span><span class="nx">speedX</span> <span class="o">=</span> <span class="nf">randomize</span><span class="p">();</span> <span class="c1">// randomly start going left or right</span>
  <span class="nx">ball</span><span class="p">.</span><span class="nx">speedY</span> <span class="o">=</span> <span class="mi">0</span><span class="p">;</span>
<span class="p">}</span>
</code></pre></div></div>

<hr />

<p>This is the main logic of Pong. However, it’s not perfect, and it could be improved a lot in several ways… for example by implementing <strong>physics rules</strong> (or by using a physics engine, that has already done the job for us). We have just simulated the reflection of a ball on a surface, but it’s not realistic at all - let’s make it better.</p>

<h2 id="the-hard-way">The “hard way”</h2>

<p>In a <em>proper</em> Pong game, you can usually control where the ball goes. It could have a steeper or shallower angle of reflection, based on where the ball landed. Should it land on one of the edges of the paddle, the collision should be inelastic. In case it lands exactly on the middle of the paddle, the collision should be <a href="http://hyperphysics.phy-astr.gsu.edu/hbase/elacol.html" rel="external">totally elastic</a>.</p>

<p>In order to implement physics rules in a game, you should have an understanding of basic vector math, trigonometry and - of course - physics. But don’t fear, you don’t have to know everything: just the basics. I personally didn’t know much about physics, but I learned it by reading about it.</p>

<p>Here are some useful resources on the Web:</p>

<ul>
  <li>Math lessons: <a href="//www.mathsisfun.com/" rel="external">www.mathsisfun.com</a></li>
  <li>Physics lessons: <a href="//www.physicsclassroom.com/" rel="external">www.physicsclassroom.com</a></li>
  <li>Vector math cheatsheet: <a href="http://higherorderfun.com/blog/2012/06/03/math-for-game-programmers-05-vector-cheat-sheet/" rel="external">higherorderfun.com/blog/2012/06/03/math-for-game-programmers-05-vector-cheat-sheet/</a></li>
  <li>Linear algebra for game developers: <a href="//blog.wolfire.com/2009/07/linear-algebra-for-game-developers-part-1/" rel="external">blog.wolfire.com/2009/07/linear-algebra-for-game-developers-part-1/</a></li>
</ul>

<p>Let’s explore together the potential of 2D vectors.</p>

<h3 id="using-2d-vectors">Using 2D Vectors</h3>

<p>The main thing you’ll have to understand is how vectors are used in game development. As an example, let’s go back to our <code class="language-plaintext highlighter-rouge">ball</code> object and modify it to use vectors. It will look like this:</p>

<div class="language-javascript highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kd">var</span> <span class="nx">ball</span> <span class="o">=</span> <span class="p">{</span>
  <span class="na">position</span><span class="p">:</span> <span class="k">new</span> <span class="nc">Vector</span><span class="p">({</span> <span class="na">x</span><span class="p">:</span> <span class="mi">0</span> <span class="p">,</span> <span class="na">y</span><span class="p">:</span> <span class="mi">0</span> <span class="p">}),</span>
  <span class="na">velocity</span><span class="p">:</span> <span class="k">new</span> <span class="nc">Vector</span><span class="p">({</span> <span class="na">x</span><span class="p">:</span> <span class="mi">0</span> <span class="p">,</span> <span class="na">y</span><span class="p">:</span> <span class="mi">0</span> <span class="p">})</span>
<span class="p">}</span>
</code></pre></div></div>

<p>Four values at the price of two attributes! And this is a lot better now, not only because we are using less attributes, but because we can use vector math. Believe me, vectors simplify your game a lot.</p>

<p>You may have noticed that I didn’t use <code class="language-plaintext highlighter-rouge">speed</code>, but I used <code class="language-plaintext highlighter-rouge">velocity</code> instead. The reason is that <code class="language-plaintext highlighter-rouge">speed</code> is a <em>scalar</em> quantity, while <code class="language-plaintext highlighter-rouge">velocity</code> is a <em>vector</em> quantity. Put simply, <code class="language-plaintext highlighter-rouge">speed</code> is an information that’s <em>contained</em> in <code class="language-plaintext highlighter-rouge">velocity</code>! You may want to <a rel="external" href="//www.physicsclassroom.com/class/1DKin/Lesson-1/Speed-and-Velocity">read about it</a>, albeit not directly related to programming.</p>

<h3 id="a-proper-ball-reflection">A proper ball reflection</h3>

<p>We can implement proper reflection (not a fake one) by using this JavaScript function:</p>

<div class="language-javascript highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kd">var</span> <span class="nx">ball</span> <span class="o">=</span> <span class="p">{</span>
  <span class="c1">// the velocity vector</span>
  <span class="na">velocity</span><span class="p">:</span> <span class="k">new</span> <span class="nc">Vector</span><span class="p">(),</span>

  <span class="cm">/*
  * The formula:
  *
  *  R = 2(V · N) * N - V
  *
  * V: velocity vector
  * N: a normalized vector of the plane surface (e.g. paddle or wall)
  * R: the reflected velocity vector
  */</span>
  <span class="na">deflect</span><span class="p">:</span> <span class="nf">function </span><span class="p">(</span><span class="nx">N</span><span class="p">)</span> <span class="p">{</span>
    <span class="kd">var</span> <span class="nx">dot</span> <span class="o">=</span> <span class="k">this</span><span class="p">.</span><span class="nx">velocity</span><span class="p">.</span><span class="nf">dot</span><span class="p">(</span><span class="nx">N</span><span class="p">);</span>
    <span class="kd">var</span> <span class="nx">v1</span> <span class="o">=</span> <span class="nx">N</span><span class="p">.</span><span class="nf">multiplyScalar</span><span class="p">(</span><span class="mi">2</span> <span class="o">*</span> <span class="nx">dot</span><span class="p">);</span>
    <span class="k">this</span><span class="p">.</span><span class="nx">velocity</span> <span class="o">=</span> <span class="nx">v1</span><span class="p">.</span><span class="nf">subSelf</span><span class="p">(</span><span class="k">this</span><span class="p">.</span><span class="nx">velocity</span><span class="p">);</span>
  <span class="p">}</span>
<span class="p">}</span>

</code></pre></div></div>

<p>This is how I’ve implemented it by using a vector library I found on the Web (find the <a rel="external" href="https://github.com/dudeOMG/pong/blob/master/js/vector2.js">source code on GitHub</a>). Given a paddle’s normal, it will reflect any vector, but you have to make sure the paddle’s normal is a unit vector (in other words, it’s <em>normalized</em>).</p>

<h2 id="conclusion">Conclusion</h2>

<p>I hope you enjoyed this article. Who’s following my blog since the beginning will probably remember <a href="/playing-around-with-javascript/">my first blog post</a>. It was more than 2 years ago, and at that time I was really excited by the idea to build a game with JavaScript. I finally did it, and it has been fun indeed! However, I learned a big lesson: although it was fun, it wasn’t really worth reinventing the wheel.</p>

<p>So, if you got through all this tutorial, first of all congratulations! Secondly, consider using a game engine. Thirdly, maybe consider <em>not</em> using JavaScript… just use whatever you feel comfortable with. For instance, if you like the Ruby language (<a href="/ruby-is-magic/">I do!</a>), you could use <a rel="external" href="//opalrb.org/">Opal</a>, a Ruby to JavaScript compiler.</p>

<h2 id="demo-and-source-code">Demo and source code</h2>

<p>You can <a href="/games/pong/">play the game here</a>.</p>

<p>The <a rel="external" href="https://github.com/dudeOMG/pong">full source code</a> is on GitHub so you can clone it, fork it and even make your own from scratch, if you feel like it’s worth your time. If you are interested in the simple way, checkout the <a rel="external" href="https://github.com/dudeOMG/pong/releases/tag/v1.0">v1.0 release</a>.
The hard way is in the master branch.</p>

<p>As always, if you have any thoughts or questions, feel free to leave a comment below.</p>

<p>Have fun!</p>

]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[Install Sublime Text 3 on Linux]]></title>
    <link href="https://simonewebdesign.it/install-sublime-text-3-on-linux/"/>
    <updated>2014-09-01T12:35:34+00:00</updated>
    <id>https://simonewebdesign.it/install-sublime-text-3-on-linux</id>
    <content type="html"><![CDATA[<p>There are <a ref="external" href="http://sublime-text-unofficial-documentation.readthedocs.org/en/latest/getting_started/install.html#linux">many ways</a> of <strong>installing Sublime Text 3 on Linux</strong>, but if you’re looking for a fast, straightforward way, I believe you are in the right place.</p>

<p>This script will install <strong>the latest build of Sublime Text 3</strong>.</p>

<p>Open your terminal and run:</p>

<div class="language-bash highlighter-rouge"><div class="highlight"><pre class="highlight"><code>curl <span class="nt">-L</span> git.io/sublimetext | sh
</code></pre></div></div>

<p>It will install the <a href="https://sublime.wbond.net/" rel="external">Package Control</a> as well, so you don’t have to do it yourself.</p>

<p>If you are interested to see the actual code behind, here we go:</p>

<p><a href="https://gist.github.com/simonewebdesign/8507139">https://gist.github.com/simonewebdesign/8507139</a></p>

<p>It should work on most Linux distros; if not, please let me know by leaving a comment below. I’m here to help.</p>

<p>Enjoy!</p>

<p><strong>Update</strong>: When I wrote this script, my motivation was that there was no easy way to install Sublime Text on Linux. However, nowadays there is an official repository providing builds for all the major Linux package managers: <a href="https://www.sublimetext.com/docs/3/linux_repositories.html" rel="external">see here</a>.</p>
]]></content>
  </entry>
  
</feed>
