<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Adam Mackintosh on Medium]]></title>
        <description><![CDATA[Stories by Adam Mackintosh on Medium]]></description>
        <link>https://medium.com/@agm1984?source=rss-62ac59fdc132------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*duTVIY_Z7FPk-Lvn0docEQ.jpeg</url>
            <title>Stories by Adam Mackintosh on Medium</title>
            <link>https://medium.com/@agm1984?source=rss-62ac59fdc132------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 19 Nov 2026 00:14:53 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@agm1984/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[An important note to all developers, network-stakeholders, and intellectuals about algorithmic…]]></title>
            <link>https://agm1984.medium.com/an-important-note-to-all-developers-network-stakeholders-and-intellectuals-about-algorithmic-25b5703aa953?source=rss-62ac59fdc132------2</link>
            <guid isPermaLink="false">https://medium.com/p/25b5703aa953</guid>
            <category><![CDATA[algorithms]]></category>
            <category><![CDATA[abuse]]></category>
            <category><![CDATA[calculus]]></category>
            <category><![CDATA[hacking]]></category>
            <category><![CDATA[bots]]></category>
            <dc:creator><![CDATA[Adam Mackintosh]]></dc:creator>
            <pubDate>Tue, 10 Nov 2020 18:02:01 GMT</pubDate>
            <atom:updated>2020-11-26T18:07:37.562Z</atom:updated>
            <content:encoded><![CDATA[<h3>An important note to all developers, network-stakeholders, and intellectuals about algorithmic abuse (a post-hoc analysis of a case of Facebook Ads abuse)</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bKic1Pu6Mo8jUoRkPAsDMw.png" /><figcaption>Fig 1.0 — Algorithmic Abuse</figcaption></figure><p>Allow me to preface this article by saying, you don’t need knowledge of every word to understand my overall point. If you bind up on a term, try Googling it, or ask for clarity. Leave a comment at the bottom if you find anything confusing. I will clarify it for the next person.</p><p>For TLDR, in this article, I have bolded my top 3 main points.</p><h3>Introduction</h3><p>I just noticed, about a month ago, I made a comment in a software developer subreddit, and it was downvoted to -6. It was in reply to this post: <strong>How A Software Engineer Used Facebook Ads To Land An Interview at Reddit</strong> (Source: <a href="https://www.reddit.com/r/ExperiencedDevs/comments/hmivns/how_a_software_engineer_used_facebook_ads_to_land/">https://www.reddit.com/r/ExperiencedDevs/comments/hmivns/how_a_software_engineer_used_facebook_ads_to_land/</a>)</p><p>I said,</p><blockquote><em>I like to see this algorithmic abuse phenomenon circulating more.</em></blockquote><blockquote><em>This is a clever use of calculus to push data into the CEO’s closure. Such a prime filter seems to be a derivative.</em></blockquote><blockquote>Note, a closure is simply an enclosed area — in this case, the CEO’s life.</blockquote><p>In that above reply, I forgot to include <em>why</em> I said “I like to see this”, and I think my reasoning is extremely important to make better-known.</p><p>Following this is my reasoning in expanded form.</p><h3>Analysis</h3><p>I don’t like to see unethical behaviour such as using a back-door to force some CEO to see something; what I like to see is discussion around this usage of literally Calculus to take a shortcut somewhere precise using what is available. I like to see discussion around the abuse of algorithms because I see so much algorithmic abuse. We need low-level discussions like this to understand how we can fix such a rampant societal problem.</p><p>The Calculus here is this:</p><blockquote>the limit of the result set being a specific CEO approaches 100% probability as the set of filter criterions approaches a specific set.</blockquote><p>The abuse is that Facebook doesn’t/didn’t seem to have a concept of public/private properties of users with respect to ad-filtering logic with respect to the user’s authorization-level, or the abuse is that the “create ad function” allowed an arbitrary user to cross an ethical boundary. For example, if a person can transform themselves into a vehicle’s interior, the door locks are simply an inadequate solution while an exterior person has permission to execute the unbounded transformation function. Something additional is needed, but we need to first identify the transformation function in order to block its use <em>effectively</em>. Generally, everything well-characterized can be well-solved by engineers.</p><p>Here, I don’t propose a solution, but I continue to be impressed by the fact that someone derived pure logic that cuts through network behaviour and security boundaries in order to use equational reasoning with the right-side of the equation being = Ronald McDonald CEO of McDonalds.</p><blockquote>The abuser derived the left-side of the equation.</blockquote><p><strong>To me it highlights a class of InfoSec attack vectors that I call algorithmic abuse. An algorithm exists, and someone took advantage of its rigid behaviour to derive an advantageous outcome (ie: a selfish objective with negative externalities</strong> — <strong>the CEO was forced to smell hot garbage).</strong></p><p>My warning — that I totally failed to describe in my comment a month ago — is that this occurs elsewhere too, in other forms. YouTube and Reddit display the greatest-upvoted comments on a node to all users, so if a person wants all users to view their bad actor content, the person uses VPNs and bots to fraudulently upvote their node-comment in a manner that YouTube and Reddit can’t detect.</p><p>This line of reasoning goes straight into graph theory and AI, and my warning is that we are still in infantile days, so these abuses of algorithms occur in large numbers everywhere; <strong>therefore, I like to see the idea of algorithmic abuse discussed and propagated, and I want to see all socially-important types of abuse identified and commonly known</strong>. This is certainly a branch of science: the study of algorithmic abuse. I don’t know if that exists yet in the precise form. Legislation should exist to force websites to adhere to network logic that prevents all forms of abuse. We should make this easy for them.</p><p>If you create a new website now that has an upvote mechanism, you are instantly vulnerable to VPNs and bots that take advantage of your lack of protection against not only that mechanism but also every known abuse type on every mechanism used by your website — including externally-controlled mechanisms. The loser in this? Every person that makes contact with fraudulent content.</p><p>As one example, it should be mandatory for elementary school students to identify by name all types of abuse that will occur to them in their formative years. The authority of YouTube is one coefficient, but the authority of a YouTube commenter is zero in that interface. At what level of education is ‘authoritative sources’ learned? For me it was grade 12 or first year of university. Without that learning, public is subject to digital grifters that are spraying entropy into society from their outlets.</p><h3>Conclusion</h3><p>By all means, please digest what I’m saying and produce downstream public articles, videos, and legislation that makes these attack vectors commonly known. People can use their domain-expertise to identify types of algorithmic abuse, and people can catalogue them by name. <strong>Our digital immune system is not developed enough.</strong></p><p>The first step is awareness. The next step is solution. We can accelerate progress if the majority of people are on the look-out for specific types of threats. I might even argue that knowing something about algorithmic abuse is the contemporary version of ‘looking both ways before crossing the street’.</p><p>In many ways, the digital world runs parallel to the real world. While we are looking for ways to sanitize public areas in the real world, we should be using this pandemic to look for ways to sanitize the internet too. How different is coughing on someone in the real world compared to displaying a fake product review on Amazon that is upvoted by bots? In both cases, they can experience bad news later. Remember, what has been seen cannot be unseen. Viral data can create a chemical reaction in your thinking processes.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=25b5703aa953" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to make AGI better than today (Sept. 8, 2020)]]></title>
            <link>https://agm1984.medium.com/how-to-make-agi-better-than-today-sept-8-2020-31ab4be37f73?source=rss-62ac59fdc132------2</link>
            <guid isPermaLink="false">https://medium.com/p/31ab4be37f73</guid>
            <category><![CDATA[functional-programming]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[frp]]></category>
            <category><![CDATA[agi]]></category>
            <category><![CDATA[calculus]]></category>
            <dc:creator><![CDATA[Adam Mackintosh]]></dc:creator>
            <pubDate>Tue, 08 Sep 2020 23:22:39 GMT</pubDate>
            <atom:updated>2020-09-11T06:16:57.615Z</atom:updated>
            <content:encoded><![CDATA[<h3>How to make Artificial General Intelligence (AGI) better than today (Sept. 8, 2020)</h3><h3>Preface</h3><p>One thing I find constant is that it’s extremely difficult to ascertain where humans are at today. So I am inclined to reduce my confidence in the article’s headline. I am also inclined to cite “With these words, I can sell you anything” by William Lutz because it details weasel words and double-speak in advertising. Call that a referential transparency pre-requisite, and call this article some kind of reference material for beginners or experts that just need a novel keyword or two.</p><p>I first wrote this article as a comment on the, at this moment, newest Two Minute Papers video on YouTube, but then I realized, to increase anti-fragility magnitudinally proportional to the decrease in fragility, I should place it here also. I will edit it <em>to some degree </em>for better readability on Medium. I posted other gems composed with garbage on Twitter; if you want them bad enough, you can find them.</p><p>The original video is here:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2F5NM_WBI9UBE%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3D5NM_WBI9UBE&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2F5NM_WBI9UBE%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/9687fce2d9652b73196d5effc8dda7d9/href">https://medium.com/media/9687fce2d9652b73196d5effc8dda7d9/href</a></iframe><p>You can maybe see me rabble-rousing in the comments section there (but it’s the same content, so don’t~ bother).</p><p>Continuing on,</p><p>If you are a researcher (do not TLDR this), due to things I’ve heard Eric Weinstein say, I would like you to brush up on Principle Fibre Bundles, and see if you can appeal to any of that logic and figure out how to do two separate things:</p><p>The Weinsteins are always significant to me because they are like Einstein twins, and as you can see, they take the upstream W and operate objectively.</p><p>Maybe I can link these videos with context-timestamps soon.</p><blockquote><strong>Semi-contextual note:</strong> In my coffee this morning after stirring, there was one large bubble in the middle, followed by a sphere-packed set of variable-sized node-like bubbles. Overall shape was circular, but slightly deformed. After a period of time slowly rotating, it stuck to the wall of the cup. It was certainly both a graph and a clique.</blockquote><p>If you find any assertion or application of logic in this article that you want attributed to someone, place it in the comments. I am experienced with the APA style guide, and I would love to augment related material in this context. Stated comically, this model has arguably some class.</p><p>Oops, two things:</p><h3>1) Transforming data while systems of equations</h3><p>Figure out if anything you’re working on can benefit from the idea of having either 3 equations equated, or 6 equations equated. For example, X/Y = Z/T = F/G (or double the amount of equalities), and then figure out if you can use systems of equations while data is static to make transformations to solve for unknowns. Beyond 1 unknown or 1.5 unknowns is an increase in confidence, such as 1.6 over pi which is greater than 50% confidence — maybe enough to act on a hunch.</p><p>If you watch all of Weinstein’s Rogan and Geometric Unity podcasts (there’s at least 5–10 podcasts), you’ll see like 15–30 hours of him describing things you need to understand. Think of the movement of data in video keyframes as what it is, deltas of X, Y, Z, T, and spin, and deltas towards increases or decreases in efficiency or effectiveness.</p><blockquote>Try to find unitless units.</blockquote><h3>2) AGI is a recurrent multi-step algorithm of multi-step algorithms</h3><p>Think about AI parsing <strong>video</strong> as maybe a multi-step algorithm that does some strategy similar to how a human thinks, and figure out that order, such as:</p><h4>Establish boundaries</h4><p>Find constraints for an agent’s behaviour (so you can efficiently traverse less area by rejecting garbage basins of attraction). Find the convex and concave boundaries in~ which some kind of dynamic equilibrium is before, now, and/or after maybe. Is it converging to garbage? Reject it. Think in 3D so you might need more equations to solve one unknown across two frames (ie: moments). Think about an agent’s behaviour in terms of magnetism, polarity between -1 and 1.</p><blockquote>For example, if a humanoid has orange crayon contacting black construction paper. I mean maybe note and track the Halloween symbol in your associative memory, but I more so mean obviously their <strong>intent</strong> is to draw something for the <strong>purpose</strong> of joy or another symbol of interest in the context. Obviously there is some vector(s) towards a <strong>reward</strong> or <strong>danger</strong> symbol in this context. You might derive those from the <strong>outcome</strong> being converged upon.</blockquote><p>I notice currently, most robots don’t instantly ask, “why?” when they encounter something they don’t understand. They seem to love to waste their time calculating changes in my lip angle while my mother is putting on lipstick. Did she say anything recently that relates to lipstick?</p><p>Please watch this video here of Richard Feynman:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FP1ww1IXRfTA%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DP1ww1IXRfTA&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FP1ww1IXRfTA%2Fhqdefault.jpg&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/85d7dadb59117eadded83f956c3c3cb7/href">https://medium.com/media/85d7dadb59117eadded83f956c3c3cb7/href</a></iframe><p>Listen ultra-carefully when he talks about someone asking him how magnetism works, and he goes off on a ‘tangent’ explaining why he could recurrently ask why everytime someone gives him an answer. Literally within seconds or minutes (highkey: moments), the person is forced to talk about the Big Bang, and our answer is probably trending towards inaccurate and/or imprecise. Uh oh. (ie: Scooby Doo sound)</p><blockquote>He is saying, one can always <strong>look upstream</strong>. One can always pretend a strict equality is a loose equality and consider if there’s a better answer there upstream.</blockquote><blockquote>Please do not ever forget that. Are you satisfied with my answer here? Why?</blockquote><p>When I first wrote this article and published it, I didn’t realize the full implications. It required me to send a positive Tweet to Gad Saad about costly-signals and black swans. This morning while re-reading my own article, I notice the important takeaway from the above “Big Bang” mention is that, what exactly would your AGI do if a black swan delta occurred from a costly signal? It would set some predicate to truthy and propagate it throughout the entire brain, for use in every consideration and/or action.</p><p>The point of me incrementing the paragraph count in this article to include the above paragraph, is that, if a child function learns of this information, how does it communicate not just discrete scalar values but also continuous functions? How does the system backfill (note: excavator backfilling dirt into a hole, maybe shaping subjectively) this new function everywhere it is applicable? And, how does it magnify its total crystallized intelligence and fluid intelligence through the network effect of that operation? I suspect that operation occurs recurrently until the network effect of network effects reaches zero new additions~ and/or subtractions~.</p><p>A bit into this article, I will link my Functional Programming article, and you must read it to understand how I approach predicate references (discrete) and predicate functions (analog/continuous) as a method of trapping and decoupling, exactly like hunting beavers in Canada in the 1800s, except totally different. You’ll find a boolean you like. I guarantee it.png</p><blockquote><strong>Quick aside:</strong> Imagine a camera shutter closing in. Next, imagine a composition of boolean constrictors starting from a scaffold and back-filling inward until the obvious solution is there. Now, imagine the inverse of that — or maybe the converse.</blockquote><p>Further (and back to the crayon example above), what are the boundaries and constraints here that minimize cumulative symbol possibilities? Cultivating joy is a fascinating cyclical dependency of sorts. In Philosophy, they might reference intrinsic pleasure. Is it that the intent and purpose are the reward? If there is movement occurring, both higher-order and lower-order tangents could be moving too.</p><p>Don’t forget turning points are related to power rule and second derivative tests, etc. Simple math is better than complex math. Simple behaviour vectors are better than complex. Identify the boundaries. If some agent is converging on a dog, maybe it’s seeking to maybe pet or maybe eat. What are the top probabilities, and how can you draw a boundary around what’s important in that context. I use the idea of spectral functions. If you know how an agent will act in a context, it’s kinda like a spectral function that draws a behaviour-related path detection map.</p><p>In the agent/dog example, consider the difference between an agent smiling and an agent grimacing with a knife in hand. Why parse deeper when those two behaviours are instantly inverse? What if he said “don’t worry buddy” and appears to be cooking and his orientation to the dog is slightly off because he needs to cut a camping tent wire? What if his orientation changed in the last few moments, firing a “converge target switched” event away from the wire towards the dog, causing the agent to frog-style jump at the agent?</p><p>Basically all I’m saying is a lot, and most of it has to do with allowing your robot some freedom in jumping through dimensions. If your brain doesn’t undergo inelastic collisions with my way of of thinking so far, maybe check out my article about functional programming. I want to make sure you have that way of thinking unpacked:</p><p><a href="https://medium.com/@agm1984/an-overview-of-functional-programming-in-javascript-and-react-part-one-10d75b509e9e">An intro to Functional Programming in JavaScript~ (and React and/or Vue)</a></p><p>Don’t balk at the mention of JavaScript, React, and Vue there. If the tangent of your emotion just suddenly increased towards negative polarity while decreased towards positive polarity, then you need to read that more than you think. A person must deeply understand tubes, pathways, and closures to deeply understand <strong>context</strong>.</p><p>Back to that Feynman video above, for a moment. Listen also mega-carefully when he talks about being trolled by MIT peers about seeing his own reflection. “What is your reflection?” he talks about.</p><blockquote><strong>Spoiler alert:</strong> if you haven’t watched the above video yet, but…</blockquote><p>Your reflection is the image of yourself that is inside-out and backwards. Do you know what else is inside-out and backwards? Function composition:</p><blockquote>f(g(h(x)))</blockquote><p>Isn’t that fascinating how x must exist before it goes into h() before it goes into g() before it goes into f()?</p><p>I haven’t found any fantastic material about this besides Feynman in that video, but to me this means that the Universe is declared first and then executed after inside-out and backwards. To me, this means think before you act, consider before you catalyze or perform action towards outcome. My remaining question is, how much thinking first? I leave that up to you as the optimizer of your robot’s efficiency &amp;&amp; effectiveness.</p><h4>Orientation &amp;&amp; Precession</h4><p>b) Don’t forget about precession and orientation in the 2D and 3D spaces. These can relate to any number of agents in the hyperspace due to incentives (pull agent towards symbol), motives (push agent to symbol), rewards (push agent to symbol), dangers (pull agent from symbol). I see a juicy apple. I’m hungry event published. I see a bear near it. Incentive dropping now. Stop action event. Push towards next idea about hunger. Imagine publishing and subscribing and listening for events and actions, Make your agents study deltas between state changes, and make them use systems of equations to chop out noise and calculate something optimal in the next frame. This is how functional-reactive programmers think about how an application’s state changes. Hyper-dimensional dynamic equilibrium must exist.</p><p>Avoid superfluous re-renders by ensuring lower-order components only re-render when their props or state change. Use sideways data-loading if state must pass wild distances or to specific closures.</p><blockquote>Bonus: I’m not 100% sure here, but maybe use event emitters or callbacks to pass functions; feel it out… <strong>make it work first, then make it better</strong>.</blockquote><p>Given the formula:</p><blockquote>ui = fn(state)</blockquote><h4>user interface = the recurrent render function of the current state</h4><ul><li>This is no different than <strong>y = f(x)</strong>.</li><li>Notice how the deltas are magnitudinally proportional.</li><li>As <strong>y</strong> changes, <strong>f(x)</strong> changes by the exact same amount to maintain the balance of the equality.</li></ul><p>Don’t forget about loose or strict equality in crazy situations. Make your agents anti-fragile to the difference between loose and strict equality. Why do you think TypeScript is better than JavaScript except when it isn’t? Interesting: dynamic typing and static typing. Interesting: asynchronous and synchronous functions, function composition, object composition. Study these if you don’t feel confident. Study pub/sub. Push an action. Pull an event by unique name. Transform event-detection to action-initiation (catalyze or perform).</p><p>Now, hold onto your papers and re-read this “Orientation &amp;&amp; Precession” section and unpack <strong>symbol</strong> to “either a discrete object or a continuous function”.</p><blockquote>Oh wow: so elusive yet so obvious and critical if we like to aim towards particle/wave duality.</blockquote><h4>Declarative vs. Imperative</h4><p>Think more often in terms of how a parent dimension REALLY relates to a child dimension when you are looking for shortcuts due to computation efficiency and memory storage. A parent is above, so it can contain the compressed/packed/abstracted version of something. When you zoom in, you go from parent to child maybe.</p><p>Is the parent “camera does stuff” while the child is “this is how camera does stuff”? Zoom in 10% child. Ok parent we zoomed in 10% — here’s what changed, but wildcard-symbol Jim I’m a doctor not a Star Trek reference. Ok zoom in another 5% but add a blue filter and tell me what you got.</p><p>How does data fight to go back upstream? or how do we think about parent/child movement?</p><ul><li>In React JS, we call that lifting state and/or continuation passing style.</li><li>Vue JS uses event emitters more often to cross-pollinate closures.</li><li>Newton and Leibniz probably use differential equations to integrate what the state change was, but that’s implicit and yucky compared to explicit state changes with Mealy finite state machines.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/817/1*eJg-p2DvCkRSUVimd_VDXw.png" /><figcaption>Fig ?.? — NP != P</figcaption></figure><p>Quick side here, but I want to show this napkin math above because it relates to NP != P. You can see visually why it is hard for some agents to understand context while easy for others, and why it’s near-impossible for some agents to verify accuracy &amp;&amp; precision while near-easy for others.</p><p>To understand the image, consider the chain as a directed graph where each node is a closure that has context, but there is no communication from downstream to upstream. It makes it pretty obvious why the node with awareness as no problem verifying while the other one isn’t so “lucky”.</p><h4>Node 1 (the top circle)</h4><ul><li>has knowledge of all upstream nodes</li></ul><h4>Node 2 (the bottom circle)</h4><ul><li>has no knowledge of upstream nodes, and so cannot ascertain true quality and relevance to, well anything towards everything</li><li>this is an artifact of directed acyclic graphs where child closures cannot reach into parent closures unless the parent provides a function to do so</li><li>additionally, child closures have no awareness of what upstream nodes are connected to sibling closures unless they are connected to the context\</li></ul><p>I put this image and description below the mentions about React, Vue, and Calculus because it relates to them. Calculus allows inference based on integrating differentials, but sometimes equality is only loose not strict. And to avoid any confusion, this is due to referential transparency.</p><p>Moving on,</p><p>Where are the boundaries there that allow you to ignore Hilbert Space explosions and to prevent accidental positive feedback loops such as n+1 iterations (as seen in GraphQL). Drawing boundaries around behaviour in terms of a convex upper boundary and concave lower boundary and prime line midpoint between them can allow you to chop out noise and focus on what matters frame by frame. Parent is overall, child is delegated zoom +1 level.</p><p><strong>Write these ideas out and track them over the next few years.</strong> Ideas related to these ideas are going to blow the door open.</p><h3><strong>Seeing: You composed with Others</strong></h3><p>I don’t even understand the full implications of this, but I want to report it because black swans can emerge from anywhere, anytime. Let’s do the action of explaining it, and then see the event of the completed action. I first saw this meme a few years ago on Twitter when <a href="https://medium.com/u/e986f7cdb458">Cory House</a> posted it.</p><p>I recall it related to possibly some Psychology research. If anyone can identify the source, please drop a comment below and they can be cited, and I will drag the citation up here.</p><p>A person can use their reflection to see the unknown side where no one told them a note that says “kick me” was on it. Based on my observations, this is exactly what the integration of differentials embodies. To me it connects the idea of seeing an object (or a function) by studying the affect it has on things nearby, or studying the affect nearby things have on it.</p><p>To understand this intuitively, check this out:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*e0ziknVC0wqidZA-Roa5Rg.png" /></figure><ol><li>seeable by self + mentioned by others,</li><li>unseeable by self + mentioned by others,</li><li>seeable by self + unmentioned by others,</li><li>unseeable by self + unmentioned by others.</li></ol><p>This circle is important to humans. For the same reason each person should discover and optimize their blind-spots. Your agents should also triangulate your blind spots and make the agent improve them or at least track them or wonder about them.</p><p>I see this as 8 segments within 4 of 2 simple things in 1 area. Are those two simple things also objects and functions?</p><h3><strong>Outcomes</strong></h3><p>Think more in terms of outcomes instead of actions. An outcome is in the parent dimension while the actions to get there are in the child dimension. if the actions get botched, dump them or optimize them and maintain course towards a similar outcome. Maybe it’s even better than the original. The outcome is the declarative dimension, and the action is the imperative dimension. You need both and they work in tandem to create the dimension that both are in. It is almost certainly a fractal of fractals, and you should study functional-reactive programming to understand more intuition. Even just look at the juxtaposition between functional and reactive. Function = to, reactive = from. It makes a V shape with the equality in the middle.</p><p>I will edit this later to include more information, and I need to cite Lex Fridman’s podcast here. You’re short-changing yourself brutally if you aren’t watching all of Lex’s podcasts.</p><h3><strong>Equational reasoning</strong></h3><p>Quite simply, study equational reasoning and use it as often as possible to combat fuzzy logic boundaries and to maintain equilibrium as state changes. Combat tangents that lead to implosions or explosions.</p><p>I will edit this later to include more text about pi*r² because it relates to how a circle can grow in static proportions. This relates to a positive feedback loop because, a runaway freight train trends towards explosion, and by the same logic but inverse, a things can trend towards implosion. Starvation is an example of that if you cancel eating every meal. Your agents will follow this as they implement functions that catalyze or perform movement. There must be balance, and it must be protected just as much as state integrity.</p><h3>A final example</h3><p>If the robot falls off the seat and dies, why is that so easy for a human and so hard for a robot? The robot is on a thing. It shouldn’t be thinking about that situation imperatively. It should move up one dimension and see itself sitting on a seat which has a requirement to stay there, and if staying is risked or starts occurring, the inverse of that event is something like “don’t fall = re-balance from not staying”. So it can execute the don’t fall function if it was listening for a falling event. Perhaps the robot can kick its leg out or put its leg down. Which costs less according to micro and macro demands? Which hurts no one? Which maximizes continued movement towards success?</p><p>Note: this robot-chair example stems from Russ Tedrake’s Lex Fridman Podcast episode. There is a mild issue of citations in this article — in some moments, those can be resolved.</p><p>—</p><p>If you like this article, I spend most of my time thinking about functional-reactive programming, or at least composing algorithms and/or functions and objects. Some like FP or OOP. I prefer to compose them as the comical unit known as <strong>FPOOP</strong>.</p><p>We need to start pushing more actions into the stars, so study this material here closely, and use it to maximize your objective functions. Also, pun intended.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=31ab4be37f73" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to setup unit testing in a Laravel and Vue mono-repo application, with PHPUnit and Jest]]></title>
            <link>https://agm1984.medium.com/how-to-setup-unit-testing-in-a-laravel-and-vue-mono-repo-application-with-phpunit-and-jest-674df367959?source=rss-62ac59fdc132------2</link>
            <guid isPermaLink="false">https://medium.com/p/674df367959</guid>
            <category><![CDATA[vuejs]]></category>
            <category><![CDATA[phpunit]]></category>
            <category><![CDATA[laravel]]></category>
            <category><![CDATA[auth]]></category>
            <category><![CDATA[jest]]></category>
            <dc:creator><![CDATA[Adam Mackintosh]]></dc:creator>
            <pubDate>Sat, 11 Jul 2020 08:51:54 GMT</pubDate>
            <atom:updated>2020-07-11T08:51:54.178Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/617/1*ujLvOxJfZAhg5M9n5HW_Qg.png" /><figcaption>Fig 1.0 — Laravel + Vue</figcaption></figure><h3>Introduction</h3><p>To help you understand the level at which I might approach this, I will say I am aware of Kent Beck TDD, avoidance of the ice cream cone testing-style, and the idea of testing against feature list requirements and mandatory behaviour while avoiding brittle implementation details. I try to take a math, physics, and functional-programming approach to composing functions.</p><p>To help you figure out if you need to instantly bounce off this article, I will say the article seeks to provide maximum utility for those that have one repository that includes both a Laravel API and a Vue SPA app, but I might use some pure logic that is useful in other architectures. If your API is JSON-serving and your Vue app has vue-router and vuex, this article should rapidly trend towards useful.</p><p>Laravel comes preloaded with <strong>PHPUnit</strong>, so we will use that, and my preferred technique is to test against the real database, so we will use database transactions without committing mutations, so no test data will persist. This is also simpler overall, so I hope you enjoy the technique as much as I do.</p><p>The key factor is that the database is essentially read-only in test, but you can research how to use different database config while APP_ENV=testing if you want that for your use-case. CI/CD pipelines can stem fascinating, unique requirements.</p><blockquote><strong>Note</strong>: it’s important to test what we use in production. We don’t want to use anything “differently” during testing than we do in production. We should aim to test against what we use. From this reasoning, we test against the local database.</blockquote><p>Vue comes preloaded with nothing, so it’s reasonable that life can start out terrible. Similar to video games, we must start at level 1 with rag-like textiles. The question is, what tools should be picked up first? I assert we should use <strong>Jest</strong> because it will keep us maximally-congruent with test strategies used in React JS. We should aim for 1:1 techniques between Vue and React when reasonable.</p><p>I will try to keep this article efficient, and exposit as I feel needed. It is important to keep track of why we are doing something rather than just how to do it.</p><h3>Laravel</h3><p>To setup Laravel, we need to open up phpunit.xml. Open that, and paste in this nectar:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/235c046dce1db4932aa8a8f59b109253/href">https://medium.com/media/235c046dce1db4932aa8a8f59b109253/href</a></iframe><p>If you scan this above example config, you will see a couple things. There might be couple settings that are different than the default Laravel phpunit.xml file. I collected these random settings over time.</p><p>For example, it is common to use 4 salt rounds while testing because we aren’t testing bcrypt, and 4 salt rounds is faster than 10 rounds.</p><blockquote><strong>Pay attention:</strong> It isn’t a terrible idea to study each setting you aren’t using already. It’s a bad idea to paste in things without understanding their nature. You can ensure your application behaviour remains predictable. An unknown setting may increase system entropy — measure twice, cut once, and then cut again and hot-swap in prod due to unforeseen circumstances.</blockquote><p>For running Laravel unit tests, I like to keep a dedicated terminal open, and you can run the tests via the command: php artisan test.</p><h4>Test grouping</h4><p>Besides the top config settings, the first area to take a look at is the &lt;testsuites&gt; section. Here we are simply grouping tests by directory, and PHPUnit will run them in the declared order: AppLayout &gt; Auth &gt; Unit &gt; Feature. You can modify these as desired.</p><p>PHPUnit will run the files in those directories in alphabetical order. It is worth mentioning too that it is a good idea to avoid a time when a unit test depends on another unit test. That would be a form of bad coupling, and can spawn issues with shared mutable state.</p><h4>Mockery</h4><p>If you use Mockery, you can add the listener under the &lt;listeners&gt; section. You can completely omit the listeners section if you aren’t using it, or you can leave the &lt;listeners&gt;&lt;/listeners&gt; stub as a kind of way-marker for your future self — maybe it can trigger a memory or two. Maybe it’s cruft, or maybe it’s Maybelline.</p><p>As a bonus example, if you are using something like Socialite, and you want to test if Socialite calls out to an OAuth provider correctly, here’s an example of using Mockery to test an area of your codebase that calls an external API:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c220c1d88c7b0c71f6f433ce7961ae12/href">https://medium.com/media/c220c1d88c7b0c71f6f433ce7961ae12/href</a></iframe><p>If you are examining the above code and find yourself wanting more, you can check out my portfolio repo that I leave public for code-scavenging reasons: <a href="https://github.com/agm1984/vue-portfolio">https://github.com/agm1984/vue-portfolio</a> (note: the master branch will be updated soon, you might not see anything for a short while).</p><h4>Database transactions</h4><p>With Laravel’s DatabaseTransactions trait, PHPUnit will apply the settings in the .env file, and then your phpunit.xml file (note: right-to-left-precedence). Then, it will use database transactions on the currently-loaded database. Every time a unit test mutates data in the database, data will be mutated “in the transaction” and appear as normal in the database, and then after the unit test, the transaction will be rolled back. This means you can chain database mutation calls and then ‘not commit’ the changes.</p><blockquote>It is important to understand transaction commit and transaction rollback to fully appreciate this.</blockquote><p>You may need to change your testing strategy slightly, but each test by itself should not have dependencies or rely on any-more-than-required external state. This philosophy matches up well with the idea of making each test occur in a transaction wrapper and then rolling it back after each test.</p><p>If any state <em>does</em> persist through tests, I recommend blaming Laravel first, and then check if Laravel is maintaining any singletons or anything like that, possibly due to a session.</p><blockquote><strong>Extra</strong>: Here is a StackOverflow answer that is mandatory-reading for every person making unit tests in Laravel: <a href="https://stackoverflow.com/a/57941133/6141025">https://stackoverflow.com/a/57941133/6141025</a></blockquote><p>Setting up DatabaseTransactions is kind of a two-step process, but the good news is both are pretty much the same. You just need use DatabaseTransactions in two places: TestCase.php and every other unit test that makes database mutations. I like to use GraphQL terminology even in relational databases. A mutation is what it sounds like. The store changes. A mutation is a set operation, and a query is a get operation. Therefore, we likely don’t care about database transactions if we are just querying.</p><p>Here’s a quick example:</p><blockquote>TestCase.php (and for science reasons, I would consider this absolute minimal):</blockquote><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/954a525602a77d2f50e94ef541d38881/href">https://medium.com/media/954a525602a77d2f50e94ef541d38881/href</a></iframe><blockquote>SomeTest.php:</blockquote><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b451c47f0fda6126811129f14367327a/href">https://medium.com/media/b451c47f0fda6126811129f14367327a/href</a></iframe><p>After examining the above code, you can see why I said testing in transactions is logically simpler and less code, a 2-for-1 win. It is simpler logically because there is less config-related code. We are using whatever database is loaded in the .env file, and whatever data it has in it. Also, after the use DatabaseTransactions; declaration, there is no extra code in each unit test. The rollbacks are done for you. If any of your tests get screwed up, consider it a code smell nearby a potential bad news pattern.</p><h4>Laravel auth</h4><p>It took me countless hours of research and of ramming my head into the keyboard to understand how to test Laravel auth in a way that made me comfortable, and in a way that allowed me to lean upon Laravel’s features.</p><p>I experimented with Passport, Sanctum, and JWTAuth libraries, and contemplated Proof Key for Code Exchange (PKCE) auth flow, but since we are talking about a mono-repo, the server-side and client-side apps are both on the same domain, so Laravel’s auth system is quite suitable. At the moment, I recommend Sanctum if you need Cross-origin resource sharing (CORS).</p><p>I find all other options besides Laravel’s secure cookie auth system have a propensity to get hairy once you start to add JSON Web Tokens (JWT) and refresh token logic. It becomes a major concern to avoid CSRF and XSS exploits. If you venture down the JWT path, make sure you understand the PKCE protocol.</p><p>The first thing we need is to deal with Laravel’s $this-&gt;actingAs($user) problem. We would live in a subpar world if we couldn’t just call that anywhere, anytime to impersonate an arbitrary user.</p><p>I like to add a user of each type to TestCase.php:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ad7405f2cb6cc6f48d7a7f9cb67962b9/href">https://medium.com/media/ad7405f2cb6cc6f48d7a7f9cb67962b9/href</a></iframe><p>After harnessing the above code, you add stuff like this into your unit tests:</p><pre>$this-&gt;actingAs($this-&gt;adminUser());</pre><pre>// and</pre><pre>$user = $this-&gt;user();</pre><p>Those methods work nicely because, after each unit test, all mutations are rolled back, so rather than create a user every unit test, we can designate specific users to have predictable attributes, and then use the logical process:</p><ul><li>if the designated user exists, return it,</li><li>otherwise, create it and return it.</li></ul><p>After all that, you will notice that some session state somehow gets preserved across tests, which makes it hard to test the Laravel API for things that would assume state to be fully-reset after every test. To fix this, we can add this resetAuth method to TestCase.php:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0dfa744bba154742a39937c0df24c6d4/href">https://medium.com/media/0dfa744bba154742a39937c0df24c6d4/href</a></iframe><blockquote><strong>Don’t forget</strong>: make sure you read the StackOverflow post (<a href="https://stackoverflow.com/a/57941133/6141025">https://stackoverflow.com/a/57941133/6141025</a>) to understand what the above code does, and make sure you add a sufficient amount of \Log::debug()&#39;s into the code until you feel comfortable.</blockquote><p>Here is a quick sample for how to use $this-&gt;resetAuth();:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c3dc0b7a224d7f67182fb32820dc6d21/href">https://medium.com/media/c3dc0b7a224d7f67182fb32820dc6d21/href</a></iframe><p>Hyper-astute observers will notice that, technically it would still throw an error 429 after 10 attempts when the first attempt is from the previous unit test that doesn’t resetAuth. The key observation to make is that, if you switch the order of those unit tests around, the it_should_throw_error_422_with_empty_form test will fail every time by getting an error 429 instead of an error 422 because the cached auth state would still be throttled.</p><p>Moving on, if we have a feature that involves throttling the user, we need to actually test that behaviour. We need to trigger the error and make sure the server responds properly, in this case with an error 429. Our goal isn’t to test to make sure code exists at specific places related to an error 429. Our goal is to ensure the behaviour is observed at the specific time. Imagine if a breaking change in some library required a new syntax. We will catch wind of that immediately because, after 10 incorrect logins, we will see an error 429 if the throttle logic is working.</p><p>I have seen examples of people testing throttling but only checking some implementation details about it, such as if the Route middleware contains ‘throttle’. This is a good opportunity to re-visit the idea of testing against the behaviour we need to see. We must see the behaviour to prove the behaviour is working correctly. We can ignore everything in-between.</p><p>In the above example, without the resetAuth method, you would see the first unit test run which would increment the number of auth attempts by 1. Then the next test would run and the throttling would actually activate after 9 attempts rather than 10. Perhaps borderline-innocuous here, but we are relying on the imperative foreach loop to make exactly 10 attempts and then check if there is an error 429.</p><p>The point is, without resetAuth, there is auth state pollution shared across tests, and we don’t want that because it allows preceding tests to implicitly modify the behaviour of the current unit test.</p><p>Next, we can move on to the client-side.</p><h3>Vue</h3><p>Unit testing Laravel Vue with Jest presents a mild nightmare-scenario because Laravel uses Laravel Mix, and Mix controls Webpack. Webpack is browser JavaScript, and Jest runs in a node process.</p><p>We will attempt it today using <strong>Mix v5.0</strong>. If you try it with another version, be sure to investigate node_modules/laravel-mix/src/BabelConfig.js and pay attention to what version of Babel is being used, 6 or 7. This may radically affect the package.json packages. V7 uses @babel prefix. It is plausible that it could require some dancing in the .babelrc file.</p><p>At the moment based on my testing, it seems to be definitely-required to use babel-core@bridge because that allows Babel to use both V6 and V7 syntax. This is significant towards the interplay between Webpack and node.js JavaScript and Babel plugins.</p><p>One of the main benefits of Jest is that unit tests can run in parallel. A few years ago, it was said that Jest had improved performance over Mocha by 300% due to this (note: 12 to 4 minutes is 300%~). Literature may have changed since then, but you can read the article by a developer at Airbnb:</p><p><a href="https://medium.com/airbnb-engineering/unlocking-test-performance-migrating-from-mocha-to-jest-2796c508ec50">Migrating from Mocha to Jest</a></p><p>Another reason to use Jest is that your muscle memory might transform to and from React JS a little easier. I’m a fan of aiming for congruent patterns between React and Vue.</p><p>To install Jest, we need to install …some packages:</p><ul><li>@vue/test-utils</li><li>babel-core@bridge (note the <strong>@bridge</strong>)</li><li>babel-jest</li><li>jest</li><li>vue-jest</li></ul><p>I think it will be most helpful if we move through those in an order that allows us to see each’s contribution, but if you want to yolo-style install everything at once, try:</p><pre>npm install --save-dev @vue/test-utils babel-core@bridge babel-jest jest vue-jest</pre><p><strong>I don’t recommend that though because this article</strong> you are reading will suffer entropy over time as downstream package versions change and affect syntax. Instead, let’s try to naively install everything while prepared for detonations.</p><p>First, install the 3 main packages:</p><pre>npm install --save-dev @vue/test-utils jest vue-jest</pre><p>Checkout the API of @vue/test-utils:</p><p><a href="https://vue-test-utils.vuejs.org/api/">API | Vue Test Utils</a></p><p>Checkout the docs for jest:</p><p><a href="https://jestjs.io/docs/en/getting-started.html">Getting Started · Jest</a></p><p>Checkout the docs for vue-jest:</p><p><a href="https://github.com/vuejs/vue-jest">vuejs/vue-jest</a></p><p>Ensure this is in your package.json file:</p><pre>{<br>    &quot;scripts&quot;: {<br>        &quot;test&quot;: &quot;jest&quot;<br>    },<br>}</pre><p>Add an App.spec.js file in your ./resources/js/components/ directory:</p><pre>import { shallowMount } from &#39;@vue/test-utils&#39;;<br>import App from &#39;./App.vue&#39;;</pre><pre>describe(&#39;App&#39;, () =&gt; {<br>    it(&#39;works&#39;, () =&gt; {<br>        const wrapper = shallowMount(App);<br>    });<br>});</pre><p>Now, try to run Jest, and again I like to run this in a dedicated terminal:</p><pre>npm run test</pre><p>The first thing we might notice, is that Jest is somehow smart enough to find App.spec.js and attempt to run it. We can infer that some respectable default settings are likely being used. We will then notice that Jest is exploding on this line:</p><pre>import { shallowMount } from &#39;<a href="http://twitter.com/vue/test-utils">@vue/test-utils</a>&#39;;<br>^^^^^^</pre><pre>SyntaxError: Cannot use import statement outside a module</pre><p>Ah yes, the infamous <em>“I have no idea what ES6 is.” — node.js</em>. But of course, the vue-jest docs contain some helpful tips:</p><blockquote>If you use jest &gt; 24.0.0 and babel-jest make sure to install babel-core@bridge</blockquote><p>Now run:</p><pre>npm install --save-dev babel-core@bridge</pre><h4>jest.config.js</h4><p>And now, a critical issue remains, but it is described in the vue-jest docs. We haven’t instructed Jest to parse .js files using babel-jest, and .vue files using vue-jest. We need to create a jest.config.js file in the root of the repository (make sure: no . prefix):</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/cab8ad5673d1bee0f6328fca463ec70c/href">https://medium.com/media/cab8ad5673d1bee0f6328fca463ec70c/href</a></iframe><blockquote><strong>Note</strong>: after adding jest.config.js, try to run npm run test again. If you get an error about <strong>SyntaxError: Unexpected token ‘&lt;’</strong>, It’s because the config file isn’t loaded properly.</blockquote><p>.js config files are nice too because you can put inline annotations in beside wild config settings because no one will remember what purpose those settings serve.</p><h4>Webpack aliases</h4><p>I added a couple bonus items in the above example. You won’t see those in the vue-jest docs, but the moduleNameMapper key can be used for mapping Webpack aliases to specific directories, otherwise you will see errors when you import components using aliases such as:</p><pre>import SomeComponent from &#39;~/components/some-component.vue&#39;;</pre><p>Now, the final thing we need to do is clear that import syntax error. To do that, we will instruct babel to target the newest version of node.</p><p><strong>.babelrc</strong></p><p>Create a .babelrc file in your repository’s root directory, and paste this in:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/25d7fbf84092831ed4371ee361619810/href">https://medium.com/media/25d7fbf84092831ed4371ee361619810/href</a></iframe><p>Laravel-mix comes by default with @babel/preset-env, so we shouldn’t need to explicitly install that. It’s plausible you could see weirdness if you have Mix version less than v5~.</p><p>There is a danger slope. Vue uses Webpack and browser JavaScript, and Jest doesn’t care about that and runs on node.js. If you ever get any crazy errors while unit testing, don’t forget to read discussions about Jest in React. They can be relevant.</p><h3>Conclusion</h3><p>Assuming we didn’t have any horrific anomalies related to package versions and downstream implications of syntax changes, you should have achieved success.</p><p>Remember to test against behaviours that you require to always work. Remember to think functionally. Start with known input. Ensure state is correct at key moments in time. Finish with known output. Allow implementation details to be freely adjusted.</p><p>Don’t forget that if values aren’t discrete (ie: particles), they are continuous (ie: waves), and so analogue values should have locked upper and lower bounds. Make sure no values can go out of your allowed bounds.</p><p>For example, if users can specify an email of length between 12 to 255 characters, the lower bound is 12 and the upper bound is 255. We should test to make sure values that go out of bounds raise an error as soon as possible because an error always stems from somewhere, and we need to know that place ASAP so we don’t build more logic on top of something undesirable.</p><p><a href="https://www.twitter.com/agm1984"></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=674df367959" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to pass data from Laravel to a Vue/React SPA app]]></title>
            <link>https://agm1984.medium.com/how-to-pass-data-from-laravel-to-a-vue-react-spa-app-8e65042beee4?source=rss-62ac59fdc132------2</link>
            <guid isPermaLink="false">https://medium.com/p/8e65042beee4</guid>
            <category><![CDATA[blade]]></category>
            <category><![CDATA[data]]></category>
            <category><![CDATA[vuejs]]></category>
            <category><![CDATA[laravel]]></category>
            <category><![CDATA[react]]></category>
            <dc:creator><![CDATA[Adam Mackintosh]]></dc:creator>
            <pubDate>Tue, 26 May 2020 19:50:42 GMT</pubDate>
            <atom:updated>2020-05-27T04:50:49.221Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/814/1*3nNJGDQp7z-6o1mTNfBqWA.png" /><figcaption>Fig 1.0 — Source: <a href="https://learnappmaking.com/pass-data-between-view-controllers-swift-how-to/">https://learnappmaking.com/pass-data-between-view-controllers-swift-how-to/</a></figcaption></figure><p>I might not recommend using this pattern to pass hyper-sensitive information because window; however, I do like good object composition and function composition, so I appreciate the data flow channel that this pattern creates.</p><h3><strong>spa.blade.php (root layout file)</strong></h3><pre>@php<br>$config = [<br>    &#39;appName&#39; =&gt; config(&#39;app.name&#39;),<br>    &#39;jwt&#39; =&gt; [<br>        &#39;ttl&#39; =&gt; config(&#39;jwt.ttl&#39;),<br>        &#39;refresh_ttl&#39; =&gt; config(&#39;jwt.refresh_ttl&#39;),<br>    ],<br>];<br>@endphp</pre><pre>&lt;!DOCTYPE html&gt;<br>&lt;html lang=&quot;{{ str_replace(&#39;_&#39;, &#39;-&#39;, app()-&gt;getLocale()) }}&quot;&gt;<br>    &lt;head&gt; ... &lt;/head&gt;</pre><pre>    &lt;body&gt;<br>        &lt;div id=&quot;app&quot;&gt; ... &lt;/div&gt;</pre><pre>        &lt;script&gt;<br>            &#39;use strict&#39;;<br>            window.config = @json($config);<br>        &lt;/script&gt;</pre><pre>    &lt;/body&gt;<br>&lt;/html&gt;</pre><p>Once you have that technology, you can do stuff like this:</p><h3><strong>some-component.vue</strong></h3><pre>export default {<br>    methods: {<br>        handleSomething() {<br>            console.log(&#39;config&#39;, window.config.jwt);<br>        },<br>    },<br>};</pre><p>or</p><pre>this.$store.dispatch(&#39;auth/saveToken&#39;, {<br>    token,<br>    expires_in: window.config.jwt.ttl,<br>});</pre><h4>A type problem</h4><p>For example, when JWT_TTL=60 is declared in the .env file, it shows up as a string &quot;60&quot; in JavaScript. You can fix that by typecasting:</p><pre>@php<br>$config = [<br>    &#39;jwt&#39; =&gt; [<br>        &#39;ttl&#39; =&gt; (int)config(&#39;jwt.ttl&#39;),<br>        &#39;refresh_ttl&#39; =&gt; (int)config(&#39;jwt.refresh_ttl&#39;),<br>    ],<br>];<br>@endphp</pre><p>Also don’t forget about the unary plus operator in JavaScript:</p><pre>// JS TRIVIA BONUS: unary is more performant than `Number()`<br>// because it omits one `if` condition in the compiler</pre><pre>console.log(+window.config.jwt.ttl);</pre><pre>const number = &#39;60&#39;;<br>console.log(&#39;number&#39;, +number, typeof +number);</pre><h3>Conclusion</h3><p>In Laravel, anytime you want, you can effectively dump anything into one object, which is kind of an accumulation phase. Such an action is deterministic. This means it will work nicely for any read-only operations that occur at any moment in time afterwards.</p><blockquote>NOTE: Because we are in the root layout file, we are creating this object at the last moment in time before all power is delegated into the #app div. It’s the moment in time when power shifts from server to client.</blockquote><p>In Vue, you can read this object at any moment in time. The object should be immutable, but you could probably watch it reactively with computed props and/or a watcher.</p><p>The thing that I like about this pattern is that the contract between the server and client is <strong>explicit</strong>. It is a straight forward process to figure out:</p><ul><li>where config(&#39;some.thing&#39;) is being used,</li><li>where window.config.some.thing is being used,</li><li>where exactly window.config stems from,</li><li>what exactly is going into window.config.</li></ul><p>In the past, I’ve seen people use stuff like JavaScript::put([&#39;some&#39; =&gt; &#39;thing&#39;]) in Laravel, and I dislike usage of that because it makes the data flow contract between server and client <strong>implicit</strong>.</p><p>For example if someone does JavaScript::put([&#39;data’ =&gt; Some::thing()]), and some JavaScript code is reading window.data, it <em>can be</em> extremely difficult to find the Laravel code responsible for populating that state. You might have to search the codebase for all instances of data or JavaScript::put( to find it. And it’s even worse if you don’t know use JavaScript; is being used in Laravel. Imagine a large codebase you just inherited.</p><p>We must be careful how we read and write to state in async JavaScript. This is why I prefer explicit contracts whenever reasonable. All of this logic is similar to passing props down in Vue or React, from parent to child. It’s easy to see how data gets into a component, and it helps to keep functions pure.</p><p>A contrasting way to pass data would be something like a global event emitter where some unknown component emits an event to nowhere specific and some unknown component commits to action based on that event.</p><p>Here’s an example of that contrasting way in Vue JS:</p><pre>// component-a.vue<br>this.$root.$on(&#39;some-event-name&#39;, (id) =&gt; {<br>    if (id === 1337) {<br>        this.$store.dispatch(&#39;some-mutating-action&#39;, &#39;payload&#39;);<br>    }<br>});</pre><pre>// component-b.vue<br>this.$root.$emit(&#39;some-event-name&#39;, 1337);</pre><p>Bugs stemming from a pattern like that can in theory trend quickly towards difficult.</p><p>Therefore, just in case this Laravel to Vue/React data flow pattern is a rare gem, I should document it. After Laravel is done executing the root layout Blade template, it’s pretty much hands-off. Slap data down on the roof of that badboy, and you’re off to the async Promise races in JavaScript with some immutable state that came from Laravel. After that, all other client-side data stems from the client or a client-made API request. You can guarantee it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/424/1*w6r7yJtQAWDCr0p4AjhBeg.png" /></figure><p>EOF</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8e65042beee4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to use JSX with Laravel and Vue with Laravel-Mix]]></title>
            <link>https://agm1984.medium.com/how-to-use-jsx-with-laravel-and-vue-with-laravel-mix-e1061aab1b6b?source=rss-62ac59fdc132------2</link>
            <guid isPermaLink="false">https://medium.com/p/e1061aab1b6b</guid>
            <category><![CDATA[laravel-mix]]></category>
            <category><![CDATA[laravel]]></category>
            <category><![CDATA[vuejs]]></category>
            <category><![CDATA[jsx]]></category>
            <dc:creator><![CDATA[Adam Mackintosh]]></dc:creator>
            <pubDate>Thu, 11 Apr 2019 22:12:57 GMT</pubDate>
            <atom:updated>2019-04-15T04:15:26.916Z</atom:updated>
            <content:encoded><![CDATA[<p>Do you find functional components to be a nightmare in Vue due to the horrific syntax? Well then stop doing it the hard way, and use JSX.</p><h3>Adam Wathan on Twitter</h3><p>Anyone have JSX working with Vue with Laravel Mix? Can&#39;t seem to get it going 🤔</p><p>If you read that Twitter thread, you will see Adam has a name similar to mine and is recommending to use the steps exactly as shown at the URL: <a href="https://github.com/vuejs/babel-plugin-transform-vue-jsx">https://github.com/vuejs/babel-plugin-transform-vue-jsx</a></p><p>The problem is, those steps are old and now Babel v7 exists, which changed the packages we need to use to make JSX work. I couldn’t find any reference material to help me do this, so I figured it out, and now you can take the time-shortcut by following these below instructions.</p><h3>INSTALLATION</h3><p>First, install these packages:</p><pre>$ npm install --save-dev <a href="http://twitter.com/babel/plugin-syntax-jsx">@babel/plugin-syntax-jsx</a><br>$ npm install --save-dev <a href="http://twitter.com/vue/babel-plugin-transform-vu">@vue/babel-plugin-transform-vu</a>e-jsx<br>$ npm install --save-dev <a href="http://twitter.com/vue/babel-helper-vue-jsx-merg">@vue/babel-helper-vue-jsx-merg</a>e-props</pre><p>Pro-style efficient:</p><pre>$npm install --save-dev <a href="http://twitter.com/babel/plugin-syntax-jsx">@babel/plugin-syntax-jsx</a> <a href="http://twitter.com/vue/babel-plugin-transform-vu">@vue/babel-plugin-transform-vu</a>e-jsx <a href="http://twitter.com/vue/babel-helper-vue-jsx-merg">@vue/babel-helper-vue-jsx-merg</a>e-props</pre><p>Second, now you’re almost done. You just have to update the .babelrc file in your project root to this:</p><pre>{<br>    &quot;plugins&quot;: [&quot;<a href="http://twitter.com/vue/babel-plugin-transform-vu">@vue/babel-plugin-transform-vu</a>e-jsx&quot;]<br>}</pre><p>You don’t need to worry about the @babel/preset-env package because Laravel-Mix has its own config which I am too lazy to confirm, but I am pretty sure it’s already using it. While we are discussing this, you may be fascinated to know that Laravel-Mix also has its own .babelrc file and the one in your project root is compatible with it, as they are merged-somehow using magic.</p><h3>CONCLUSION</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_gXwacfA-wFIW-F65J7eAw.png" /><figcaption>Fig 1.0 — Before &amp; After Comparison (source: <a href="https://github.com/chrisvfritz/vue-3-trends/blob/master/slides-2019-03-vueconfus.pdf">https://github.com/chrisvfritz/vue-3-trends/blob/master/slides-2019-03-vueconfus.pdf</a>)</figcaption></figure><h3>BONUS TIPS</h3><p>A bit later, I will probably add to this article with some reference material for how to use JSX, but in the meantime, you could visit pages such as:</p><ul><li><a href="https://scotch.io/tutorials/using-jsx-with-vue-and-why-you-should-care">https://scotch.io/tutorials/using-jsx-with-vue-and-why-you-should-care</a></li><li><a href="https://github.com/vuejs/babel-plugin-transform-vue-jsx">https://github.com/vuejs/babel-plugin-transform-vue-jsx</a></li></ul><p>and just read about the various ways you can utilize JSX.</p><p>For example, rather than @click.prevent=”handleClick&quot;, you can do onClick:prevent={handleClick}. Rather than :value=&quot;cats&quot;, you can do value={cats}. If you want to get aggressive, you can do value={...cats}.</p><p><a href="https://twitter.com/agm1984"></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e1061aab1b6b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Functional Programming in JavaScript and React (Part Two)]]></title>
            <link>https://agm1984.medium.com/functional-programming-in-javascript-and-react-part-two-521ea9f57d30?source=rss-62ac59fdc132------2</link>
            <guid isPermaLink="false">https://medium.com/p/521ea9f57d30</guid>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Adam Mackintosh]]></dc:creator>
            <pubDate>Fri, 09 Nov 2018 00:56:02 GMT</pubDate>
            <atom:updated>2018-11-09T00:58:46.633Z</atom:updated>
            <content:encoded><![CDATA[<p>NOTE: I did not mean to publish this. But I will leave it anyway yolo style. It’s still in progress. I wouldn’t recommend reading it, but you could.</p><h3>PART TWO — THE IMPORTANT FACTORS</h3><p>The way I would like you to approach these next parts is to imagine the type of things you should and must care about in order to be an extreme baller logic spewing machine. I will get you primed up now. State. Everything revolves around state. The millisecond your state gets mangled, you are toast.</p><blockquote>State integrity is the most important thing in every app.</blockquote><p>Imagine you had a calculator that forgot which number it was at or it accidentally returned the wrong number. It would pretty much be the absolute worst calculator ever made, unless it was TrollCalculator.exe. In that case, it could be among the best at what it was designed for.</p><p>Having issues with state is a little bit like yelling out random numbers while your friend is trying to count how many people he/she sees logged in — important, important, important.</p><blockquote><strong>Did you know:</strong> Redux is responsible for managing app-wide state in a React app and provides you with a formal state change-management process?</blockquote><p><strong>Key properties of an app:</strong></p><ol><li>An app can be viewed as an Object, at a moment in time when observed</li><li>An app probably requires state</li><li>An app can respond to any event we specify</li><li>An app can initiate or facilitate any action</li></ol><p>Functional Reactive Programming isn’t something my grandma can absorb in 20 minutes while you talk to her at the grocery store, so don’t feel bad if you are confused at some times. It gets comfortable over time as you understand more patterns. Like Chess, you play Chess better once you memorize a few patterns and how they unfold over time.</p><p>Today, I would like to declare some patterns, and you can use them after.</p><p>But first, I occasionally like to give nods to other people for their incredible work in the community. Eric Elliott is one of those people, and this article here is a pre-requisite to this article. I believe it should be read three times to complete the 2D closed polygon of your understanding. Put this in your Bookmarks along with other logical gems you find:</p><h3>Reactive Programming</h3><p>Before we get to the meat of these styles, we must talk about functional programming and reactive programming.</p><blockquote>It’s a matter of describing ancestors first so that children make sense. We need the context awareness.</blockquote><blockquote><strong>Note:</strong> Adobe Photoshop has context awareness with its Healing Brush. This means you can drag the brush through an area, and Photoshop calculates optimal blending of adjacent pixels.</blockquote><blockquote>My goal is to install more context awareness into you, so you can write bulletproof apps perhaps more frequently.</blockquote><h4>Function as an Object (FaaO)</h4><p>I just made up that acronym. It’s not important. When I say Object, I mean a thing or node that could be connected to another node. JavaScript happens to excel when it comes to objects that can efficiently double as functions.</p><p>Let’s conduct a little test, so we can see a Function that is also an Object. It is a testament to the incredible efficiency that is possible in JavaScript:</p><pre>const executable = () =&gt; {<br>  executable.hello = &#39;world&#39;<br>  return executable<br>}</pre><pre>// LOOK AT IT<br>console.log(executable)<br>// =&gt; { [Function] hello: &#39;world&#39; }</pre><pre>// EXECUTE IT<br>console.log(executable())<br>// =&gt; { [Function] hello: &#39;world&#39; }</pre><blockquote><strong>Quick Mention:</strong> Check these out below — they are atomic building blocks of logic. You can build the most incredible things I’ve ever seen by simply composing these things together as if we were in some deformed Math class using ideas instead of numbers.</blockquote><pre>const function = () =&gt; {}</pre><pre>const object = {}</pre><pre>const array = []</pre><p>Think of it this way, an Object can store some state. An Array can hold a collection of Objects, and a Function is a place to do work, but like in real life, there is a purpose to that work, and that’s why it’s flow best served one-way. You do the work until you get there, and then maybe you report back or keep going. Many programming rules apply here: encapsulation, sole responsibility, etc.</p><h4>Encapsulation</h4><p>?</p><h4>Sole Responsibility</h4><p>Note how I didn’t say <strong>single </strong>responsibility. This can be confusing for people. A function should be responsible for approximately one <strong>idea</strong>. An idea could consist of more than one thing. A Function called getUserData() sounds like it is only doing one thing. Introducing another ideas, may sprinkle a bit of chaos into the idea of getting user data. A function may also processUserData()which is still doing approximately one idea, but there is room to do more as long as it’s related to processing user data. Ignore any subpar naming conventions. Naming stuff is hard.</p><p>The same rules are true when you write essays in English class. Reading a paragraph that is talking about several things is confusing to readers. ‘What is the point?’ they might say. My point right now is that there is a balancing act inside functions. You have to gain intuition towards what is correct, and that may change depending on the circumstances (ie: project requirements, ie: context). No wonder this is so confusing for seasoned programmers. It’s a one word descriptor symbol for who knows what until you see the code.</p><h4>Top 3 Symbols</h4><p>Our above FaaO app is a pretty simple app. You can look at it or execute it, but there are two key takeaways: <strong>Objects have properties</strong>, meaning you can look at them and observe facts at the moment of observation. <strong>Objects can also have methods</strong>, meaning they can perform actions or respond to events. In JavaScript, you can go ahead and execute that Object.</p><p>Moving onward (continuous forward motion = good), three things pop into the forefront immediately:</p><ol><li><strong>State</strong></li><li><strong>Actions</strong></li><li><strong>Events</strong></li></ol><p>If you drew those on paper as circles and connected them together, you would have a 2D triangle. Pretty cool? No probably not, but it is to me because I eat geometry for breakfast. A triangle is the strongest geometrical shape because it must be destroyed before it loses structural integrity. This makes people race to it in Physics and Mathematics. I love trianglios, the razor sharp cereal to start your day off right angle.</p><p>I love comedy as a tool to help describe. It’s the only way we are going to get through this material without lighting your hair on fire with the help of an accelerant.</p><p>Try to think in terms of Objects in JavaScript as traveling through water slides that are always tilted so gravity can help you. Imagine that in your head, some object bombing down the slide. Now, imagine someone violently ripped in there and grabbed the object. The scenery turns sour. This occurs inside your code as well and confuses people when they look at nice flowing Functions.</p><h3>State</h3><p>Apps generally require state management, but what is state:</p><ul><li>memory</li><li>knowledge of current moment</li></ul><p>Improperly or ineffectively managing state can turn into a nightmare with intensity that grows proportionately with the size and complexity of your app. I mention state early in this article because it’s the highest priority sub-system with which to maintain correctness. For example, if an app reports an incorrect user being logged in or an incorrect dollar amount, the quality of the app is immediately under review.</p><blockquote>I would go as far as to say that state is the single most important aspect of every app.</blockquote><p>State is the one thing that must be kept accurate and precise. Therefore, we need an official process that ensures state can maintain integrity. This is your first lesson about reactive programming. If changes to state are involved, there must be a strict process to handle propagation of changes.</p><p>Two great ways to simplify complex scenarios:</p><ol><li>Immutability</li><li>One-way flow</li></ol><blockquote><strong>Special Tips:</strong> You will be off to a great start if you try to always return something from your functions. Don’t modify things outside the function unless you need to; simply return them out of the function for the next point in time.</blockquote><p>To understand those special tips, we need to discuss shared mutable state, and side effects.</p><h4>Scary Stuff</h4><p><strong>One-way flow</strong> of information is great because it keeps interactions simple. One-way is simpler than two-way. This helps us reason about what the app is doing. It allows us to manage state in one direction. Things can be modeled with a start and a finish.</p><blockquote>Start to finish, wait that sounds like executing a Function.</blockquote><p>Remember when I said the proverbial water slide was tilted so that gravity can help you? Well, just as <em>tilting a water slide too much</em> could be a problem and make a grandma start crying even though she’s seen a lot of slides in her day, pushing data too quickly or pulling it in weird ways can cause problems. In JavaScript and also any programming language, things start to get scary when you introduce concurrency.</p><p>It’s really hard for me to write this Article because there are so many definitions that you will never see in a million years in beginner tutorials and YouTube videos. I feel a moral obligation to join them all together right now in 2018 for you and for me. I’m trying to talk about state, immutability, and asynchronous JavaScript, and all I can think is, “dang, they are going to explode if I tell them aboutdeterministic conconcurrency too early&quot;. I’m not taking the easy way out by neglecting to tell you about it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/320/1*Dm7885TmnBNywh3DQRcBcA.jpeg" /><figcaption>Fig ?.? — Arrive alive</figcaption></figure><p>We are also going to talk about deterministic transformations, so put your seat belt on and grab your chosen style of liquid beverage — preferably coffee because caffeine is a central nervous system accelerant, and preferably also chew gum because it increases oxygen delivery to your brain via mastication which increases short term memory quantity and long term memory recall quality.</p><p>I need to emotionally release all this crap and find new keywords. This Article could be thought of as a compost heap that I just created. Some people will call it garbage, but they are missing the point. Imagine all the small interactions that are possible inside a compost heap. The compost heap could give life while it is composting, and it could help you later.</p><p>React JS isn’t called React for no reason. React was designed by solving the challenges and requirements of an asynchronous, data-centric app that has 2 billion users. Perhaps you’ve heard of Facebook? Imagine the sample size that design decisions could be compared against.</p><p>I underscore the importance of state in apps because events can happen at any moment. Asynchronous and parallel conditions bring significant risk to app state because data could be lost in transit. An app needs a correct action for every event that occurs. An app that responds incorrectly to an event can only cause confusion, either for the user or in the app state.</p><h3>Actions</h3><p>Apps can perform not only actions but also operations. Operations are the big brother of actions. For example, I could calculate that <strong>1+1=2</strong> but if I never tell anyone, there will be no action. When I talk about actions, I generally mean containers that are responsible for performing work — <strong>functions</strong>. An action usually has a start and finish. Functions also usually do.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/586/1*T0ZwE6rrvzMOQjp8wb6YOw.png" /></figure><blockquote>If you want to perform an action, you probably want to execute a function.</blockquote><h3>Events</h3><p>If actions are analogous to talking, events are analogous to listening. If you are listening, you may be recording changes to state as they occur. Therefore, events probably trigger state updates. Actions can trigger state updates as well, however.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/546/1*fsHOfoD6dhXOqTuE06an6A.png" /></figure><p>Because an event can be observed, anything that can be observed has properties to observe. Therefore, most events should probably create, update, or return an Object, but only if the information might be cared about later. For example, when the mouse move event occurs, you may listen for the time when it passes through x,y: 1337, 1337. You may not wish to store any other co-ordinates unless you are a scientific researcher or something.</p><p>For example, here is a birthday party as an Object:</p><pre>const birthdayParty = {<br>  startTime: 5,<br>  endTime: undefined,<br>}</pre><p>Here is an action that inherits a huge problem due to lack of immutability during an asynchronous series of events:</p><pre>const birthdayParty = {<br>  startTime: 5,<br>  endTime: undefined,<br>  location: { ...address },<br>}</pre><pre>const driveToLocation = async (location) =&gt; {<br>  return handleDriveCar(location)<br>}</pre><pre>driveToLocation(birthdayParty)<br>  .then(badExperience =&gt; forEveryone(badExperience))</pre><pre>birthdayParty.location = { ...differentAddress }</pre><p>Birthday party state was mutated after driving started. Let’s break it down forensically:</p><ol><li>Shared mutable state existed</li><li>Asynchronous behavior existed</li><li>A mutation action occurred in parallel with another action</li></ol><p>Because the state was allowed to update during this driving action and it was not synchronous, the location changed before the action completed. If the <em>driveToLocation()</em> function is not aware of this state change, a) the change management process is subpar, and b) we see why shared mutable state is controlled by the devil — if conditions are asynchronous.</p><p>The solution could be to add the async keyword which will force the driveToLocation Promise-chain to complete before execution continues and updates the new location. Good? Not exactly. What if the birthdayParty.location mutation occurred in another file? Your async keyword plan would get destroyed immediately. This is why concurrency brings indeterminism.</p><p>The only way to fix such a nasty problem is to introduce some kind of messaging system. Here are three solution areas:</p><ol><li>Event emitters and observers</li><li>Semaphores</li><li>Callbacks (continuation-passing style)</li></ol><p>All three of these solution areas involve your code picking up the proverbial phone and talking to another area of the app for purposes of coordination.</p><p>Notice how I keep talking about events happening, problems with state, and maintaining 100% accuracy and precision during state changes. Functional Reactive Programming is a very viable way to handle these type of situations. Through all this, there are two things that shine most important:</p><ol><li>State</li><li>State changes</li></ol><p>If state changes occur properly, state maintains integrity.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*ntrZOE8YOg1NaOdfHnFFWA.jpeg" /><figcaption>Dinosaurs beginning to respond poorly to change</figcaption></figure><blockquote>Radical Quote: An app’s response to change is the most important factor towards maintaining state integrity.</blockquote><p>This is where the <strong>reactive </strong>part of Functional Reactive Programming comes from. The program is reacting to changes and not screwing anything up, preferably in crazy asynchronous conditions. This makes perfect sense in the real world where wall feeds get updated while scrolling and where cancel buttons are pressed during actions and events. State is the crown jewel, and it must be protected like an infant human must be in the real world.</p><p>I did QA for years, so trust me when I say users basically navigate around your app ramming on the keyboard. It’s not you that we have to watch out for on the road while driving — it’s everyone else.</p><p>Just as learning can precede knowing, thinking about writing code in accordance to the best patterns we are currently aware of can precede writing code. Cancelling events or actions that are in mid-flight. If your paper airplane is flying at someone’s eyeball, you should have a way to stop it. The eyeball in our JavaScript case represents the cost of time, resource use, and UX quality.</p><p>Let’s setup some imagery. We are casually floating down a stream and perhaps some objects are being plucked out occasionally, or they fade out as needed. We don’t have to be floating, our stream could be pressurized and very deep underground where it is hard to see or change things.</p><p>Some things are for sure:</p><ul><li>Traveling one way is good</li><li>Traveling downhill at the most efficient pace without pooping our pants is good</li></ul><p>I have a bit of a Physics background, so some logic of Kinematics is useful here, such as perfectly elastic collisions. It’s not the math that is important though. It’s the system intuition you get from imagining Objects in a stream abruptly changing direction, and the turbulence that would arise from those events.</p><p>Remember, we are talking about events right now. Things happen. In Physics, every action has an equal and opposite reaction, and the Second Law of Thermodynamics exists. This means side effects are real. We might not know what they are until we see your project, you should <strong>always </strong>keep on the lookout for Externalities (in the Economics sense).</p><h3>Streams</h3><p>I don’t want to talk about streams too much, but they are important to mention during reactive programming conversations. What is a stream literally? Ignoring the velocity of flow, it is a channel that water is flowing through.</p><blockquote>Do you know what else can flow through channels?</blockquote><blockquote>Data.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/569/1*R0A9OMquNMhB0Ut16iaODw.png" /></figure><p>Channels are essentially how and where Objects can move from point A to point B. Data is very fluid-like. You don’t want your data to leak.</p><p>Analogous to channels are streams:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/575/1*003ap7qbZIJ-rpauJDc6Rg.png" /></figure><p>At the very minimum, data leaks cause:</p><ul><li>Security concerns</li><li>Data loss</li><li>Bugs</li></ul><p>I’ve never heard a concrete term for the concept of data leaks in apps. Bug is probably the parent descriptor word. Let’s just focus on the fact that leaking is a thing in the real world. Maybe it’s tolerable at the time, maybe it’s Maybelline, but definitely some stream is not fully optimized.</p><p>Notice in the definition above, that real streams and data streams are both continuous. If you like Calculus, you could study them. If you don’t like Calculus, we use it to send rockets to Mars and you should. This continuous nature is useful for actions and events that happen asynchronously.</p><p>A stream has a start and a finish. There is a finite distance, a positive direction, and a negative direction. The travel path is known. The app can be designed to respond to any events along the way. It can ignore events too, but there will certainly be a formal process that is followed when changes are made.</p><p>To wrap up this section, reactive programming is about reacting to changes properly by setting up the environment to handle changes and dodging problems with state. Data can be pushed or pulled; it can be pushed into somewhere or pulled in from somewhere. Data flow is typically one-way because events with respect to time are <strong>simpler</strong>. All of this will be handled immutably because a) integrity of state is of utmost importance and b) asynchronous and parallel operations are dangerous to state.</p><p>Let’s move on. Now that we have completed the action of streaming reactive data into your retinas, you can update your mental state to reflect these learning events.</p><p>If your entire app happens to be listening to the streams of state changes, actions, and events flowing through it, it can instantly re-coordinate anything you allow it to when a specific action or event happens. After that, you can start speaking in terms of pushing things or pulling them. You could push or pull towards or away from something.</p><h4>Where &amp; When</h4><p>When doing asynchronous programming, the more simple and flat the list of steps, the <strong>less </strong>likely you are to encounter a problem. Your goal is to setup functions so that you don’t have to care about anything besides when and where to call them. They handle everything correctly based on what you supply them. If you examine React using this magnifying glass, you will see.</p><p>Does this sound familiar for other reasons? Imagine if someone posted on StackOverflow with a problem and you knew exactly where and when they were doing things incorrectly. You might help them solve it pretty quick. This is why your QA team members are obsessed with knowing what the <strong>steps</strong> were <strong>to </strong>reliably <strong>produce</strong> something weird. You tell them which functions were involved and when, and they tell the developers how to fix it quickly.</p><p>This type of when and where stuff becomes much easier when the inside of your app looks like a list of functions used at specific times. Suddenly, where and when translates into exact lines of code with exact input parameters and a list of things that went wrong. My QA brain is drooling over the prospect of those app and team efficiency gains.</p><p>Everything tends to be easier to reason about when everything is made from deterministic or at least unidirectional functions. If something appears to be wrong inside thegetUserProfile() function, there is probably only one place is your app called that, and it probably looks like a list of things to do when getting a user profile. This leads me to another area of discussion. When your app is about to make a change to something it knows about, you could call it a mutation of the app’s state, but you must go through a formal change process.</p><h4>Formal Change Process</h4><p>I know some of you are already thinking: this rascal is about to talk about <strong>Redux</strong>. Well, I go news for you — that is correct. People don’t use Redux because they love adding brutal to understand addons into an app. They use Redux because it proposes a series of mechanisms that guarantee the app never gets confused about a <strong>state change</strong>.</p><p>Change management is important like generally-one-way flow is important. Both of those are important like this animated GIF is important:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/421/1*5k-EgaLM7ki7QdG4I6sIYQ.gif" /></figure><p>That’s actually what the inside of React looks like. Gear A is like the render function in your component, and JSX is the language used inside a render function. Get used to it. HTML and CSS can appear there, but do you know what is output from a render function? DOM elements. Holy cow, we just went from the top of your app to the bottom and hit the DOM. If something changes, your app will let your app know. No one will get confused.</p><p>In less sophisticated systems or more complex systems, data can more often travel backwards through the data flow. This adds efficiency but also delivers more complexity and potential confusion. It’s like adding turbulence. You know when you look at a flowing river around some rocks and you see those little whirlpool things, and you throw a stick in there because you’re a scientist? That is what added complexity looks like. You can navigate it, but it brings at the very least some serious considerations.</p><p>You cannot achieve peak flow velocity or efficiency in a given system if there is turbulence. Turbulence isn’t really a programming term, but it gives you mental imagery of non-deterministic types of things. If a change in direction relies on randomness, it’s probably not pure.</p><h4>Network Calls</h4><p>I’ve intentionally stayed mostly away from talking about things like network calls and asynchronous disk I/O because I only want to pile so many hundred new ideas into your brain at once. When you make a network call for some data, the server could respond with <strong>different output</strong> even though you gave it the <strong>same input</strong>.</p><h4>Concurrency</h4><p>Stacked on top of that, concurrency brings with it indeterminism. Why? Race conditions. If you always fire off three guns at the same time, there is no guarantee that all three bullets will hit the ground at the same time. Remember, wind, pressure gradient force, small birds — things you cannot account for may become a significant factor and result in <strong>unreliable results</strong>.</p><p>Both network calls and concurrency are why Redux exist and why it is extremely important to care about having a formal change process. Redux is the result of asking, “how can we reasonably guarantee a problem cannot occur?”</p><p>Listen, async/await is a beautiful thing when composing functions, but it does not fully save you from problems with concurrency. I didn’t want to talk about the event loop, but we are going to have to.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/529/1*DeQ-fsHYFkGdghKsow30Zg.gif" /></figure><p>Rather than talk about that. I’ll get you to do some homework:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2F8aGhZQkoFbQ%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3D8aGhZQkoFbQ&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2F8aGhZQkoFbQ%2Fhqdefault.jpg&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/a661a28c8cc4ab11cdfc9f9487ebd139/href">https://medium.com/media/a661a28c8cc4ab11cdfc9f9487ebd139/href</a></iframe><h3>Pass-by-Reference &amp; Garbage Collection</h3><p>In JavaScript, two things are critically important to understand if you and I hope to write apps that care about proper memory use. These two things are related in that one helps with storing in memory and the other helps with cleaning the memory out.</p><p>If we don’t take care of the memory, we might get memory leaks. If you had a stream or a pipe under your sink, you don’t want to be using or allowing the word <em>leak</em>.</p><h4>Pass-By-Reference</h4><p>This can be explained in one quick animated GIF:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/1*Drz5Lwh2WtLcZdrxXg7JTQ.gif" /><figcaption>Fig ?.? — Live reference</figcaption></figure><p>If I modified the cup of coffee inside fillCup(), with pass-by-reference, I would be modifying the unique coffee cup (think Singleton). With pass-by-value, it’s a different cup of coffee even though it looks identical. This could be a blessing or a curse. Maintaining a live reference is great, but remember how shared mutable state is dangerous? Remember how side effects are dangerous? If the reference is live and real-time, to modify the cup could be to modify someone else’s coffee.</p><blockquote><strong>A Quick Test:</strong> Go try right now to modify your co-worker’s coffee and let me know if they are ok with it or if they have some kind of meltdown. Sometimes it’s ok. Sometimes it’s not. That is literally the best description I’ve ever heard for combining all these concepts. I don’t even care if you like it. I laugh at my own jokes.</blockquote><p>Now, it is obvious, but not to someone, and that’s why I fly out of the woodwork to help them understand. It’s very nice of your City to clean up your garbage provided you were nice enough to leave it somewhere for them to pick it up. Something very similar is happening deep in the bowels of JavaScript, only there is no smell associated with it. I used to wash garbage trucks when I was younger, so you can trust me on that. Very funny, but cleaning details on garbage trucks sharpened my attention to detail in other areas of life, such as QA.</p><h4>Garbage Collection</h4><p>If you are maintaining references to things, you can quickly observe them, but you can also forget to release them from memory. This is garbage collection. When a function is done executing and there are no more references to that function, your app forgets about that function and dumps it out of the memory. It gets garbage collected. The City comes and takes that garbage away.</p><h3>Functional Programming</h3><p>Functional programming is essentially about breaking your program into manageable chunks but not just any chunks. A good chunk is probably based on an event or an action.</p><p>When might a function be executed, like when is a good time to fire one up?</p><ul><li><strong>before </strong>actions or events</li><li><strong>during </strong>actions or events</li><li><strong>after </strong>actions or events</li></ul><h4>3 Phases of a Function</h4><ol><li>Detection and Collection Phase</li><li>Packaging Phase</li><li>Delivering Phase</li></ol><p>These phases are not required by any means. I mention them to help you think about the types of things people do inside functions. A phase could be more known to you by a different name. That’s okay.</p><p>In the first phase, data comes into a function and gets analyzed. Think of this stage like bank of probe sensors from Star Trek. Before anyone feels comfortable doing anything, observations should probably be made. Things could be compared, etc. It’s just good science to operate this way.</p><p>In the second phase, work is done to process the data. You could imagine a direction has been selected and now the function is working towards that. You could imagine the function analyzed whatever it needed to, and now it’s performing it’s main function, no pun intended. It may sound like the delivering phase, but it’s not quite the home-stretch yet.</p><p>In the third phase, work has been completed, and now it is delivering the final product. Imagine a postal delivery truck driving at 30mph or 50km/h, and there is a happy driver in there, excited to deliver your result set.</p><p><strong>Work</strong></p><ul><li>Power: Ability to complete a large body of work quickly</li><li>Torque: Ability to quickly start or stop work</li></ul><p><strong>Memory</strong></p><ul><li>Short term memory: Knowledge of context and working parameters</li><li>Long term memory: May be used alongside work or memory</li></ul><h4>Continuation-Passing Style (CPS)</h4><p>This is a style of programming that is cleverly disguised as callbacks in JavaScript. The shortest possible definition involves a function waiting until it gets a signal to continue to the next function. You’ve seen it before. You’ve heard of callback hell. You’ve also seen it be consistently useful when you want some code to let some other code know when it is ready.</p><p>Keep an eye on callbacks because they let your app spend as much time as needed to finish some tasks before it moves on. Callbacks give you a reasonable guarantee that the next steps in a process will wait until all necessary data is available before beginning work. It’s like waiting for the materials to arrive at a job site before bringing in the construction crew.</p><p>In asynchronous JavaScript, if you are going to have a problem, it’s probably because something happened too soon or too late. It’s just the nature of the event loop game.</p><p>Here is a bit of a visual explanation:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/692/1*7jfiG0JLMrTbgyg7nb0O0A.jpeg" /></figure><p>Callbacks can seem a bit like they are flowing backwards because they exist at the top of a function where data came from, but a callback function is called while the data is flowing forward.</p><p>From the function in which the callback is called, it’s more like a button because the function has no idea what happens after the button is pressed. Why? Because the next moments in time are handled upstream in the parent function. It has to do with separating dimensional concerns.</p><p>Callbacks allow children to be involved while free of responsibility It means, if you changed the logic inside the child and the callback is still called correctly, the parent is not affected. It means, if you changed the logic in the parent, the child is not affected.</p><h4>Monad</h4><p>[define]</p><p>There are a few things that are very important towards our goal of protecting state’s integrity:</p><ul><li>Pure functions</li><li>Side effects</li><li>Referential transparency</li><li>Immutability</li></ul><h4>Pure Functions</h4><h4>Side Effects</h4><h4>Immutability</h4><p>I’m going to tell you right now, composing functions does not work in asynchronous environments when state is unpredictably changing. State cannot be assumed correct.</p><p>One way of thinking that is helpful is to consider making an app ask for the latest state before mutating it. Race conditions are probably your main concern because 2 functions modifying state at the same time is just straight up a dangerous situation. That is to say it can be.</p><p>You would need at least a formal process for handling these changes. If you are familiar with Redux, you understand. If you are familiar with Reactive JS, you are light years ahead of an inferior symbol.</p><p>Immutable functional programming is all about first-in first-out (FIFO). This FIFO concept matches up nicely with reactive programming because it gives us a way to think about problems using one-way flows. Pure functions give both referential transparency and a strategy that utilizes FIFO to handles state changes. If the scenario is complex, we may create one function to handle it or we may create a series of functions.</p><blockquote>A series of inter-dependent functions is a chain of functions.</blockquote><p>The real star of functional programming is composition. You take function that does one thing and call it from another function. Then, you call that function from a third function. Now, you are composing functions.</p><h4>Composition</h4><p>Composing functions isn’t a new thing. Without fact checking, I think people have been doing it for thousands of years in Mathematics. You may recall from math class:</p><ul><li>f of x</li><li>g of x</li><li>f composed with g of x</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/1*ULr94VUneiLiHNSN7ChNwg.png" /><figcaption>Fig 5.1 — Function Composition</figcaption></figure><p>f composed with g of x written in JavaScript looks like this:</p><pre>f(g(x))</pre><p>It means:</p><ol><li>execute <strong>g(x)</strong></li><li>then, take the result of that</li><li>then, pass that into <strong>f()</strong></li></ol><p>You can see how people might chain them together. Composition is among the key reasons why functional programming is becoming increasingly dominant. Our code becomes more declarative when we compose functions, and <strong>declarative</strong> code is often easier to understand. Declarative means you tell the program how to act and when, and it does it. It’s like showing a horse how to get water vs. giving it water every time it needs it.</p><h4>When writing functionally, you:</h4><ol><li>declare <strong>how</strong> your program should respond to various inputs (ie: define what actions the functions do),</li><li>declare configuration settings that define <strong>what</strong> those inputs are (ie: define state at moments in time),</li><li>declare <strong>when</strong> to trigger these functions (ie: define the events your program reacts to).</li></ol><p>I selected those keywords very carefully. Moving on, we can compose not only functions but also objects when we are thinking this way. Here is an example:</p><pre>const person = {<br>  firstName: &#39;Suzy&#39;,<br>  lastName: &#39;Kawasaki&#39;,<br>}</pre><pre>const config = {<br>  host: &#39;127.0.0.1&#39;,<br>  port: 1337,<br>  user: person,<br>}</pre><pre>const connectToDB = (config) =&gt; {<br>  const connection = getDriver(config.host, config.port)<br>  return connection<br>}</pre><p>See how <strong>connectToDB()</strong> accepts the config object and how the <strong>person</strong> Object is composed inside the <strong>config</strong> Object?</p><p>Functional style code that is declarative can strike a near-perfect mix of declarative vs. imperative. Declarative means you tell it what to do. You declare it. Imperative means you tell it how to do it, which is like telling the function exactly how to operate. You need to do both. You can’t get away from both like you can’t get 100% away from Objects or Functions. There is always a mixture.</p><p>A function is like a module. It performs the work given to it by its parent. A function is also a component that is controlled by its parent. There could be limited control. The parent may say do whatever you determine is correct.</p><h3>Functional + Reactive = Modular Components</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/501/1*8sYr39LkpDVKv-aTYom8lw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/514/1*PET1vuQ1dXFABmJSWpPCeg.png" /></figure><h4>The 3 tenants of modular components:</h4><ul><li>self-contained</li><li>accepts a Config Object</li><li>external Side Effects are officially managed</li></ul><ol><li>single source of truth store/repository for standalone components</li><li>pull packages into any project via NPM or equivalent</li></ol><h4>Self Contained</h4><p>Components should be self-sufficient. I would go as far as to say they should be 100% self-sustaining as much as is reasonable. If it’s not self-sustaining, it’s dependent on something. The best components will handle all duties related to a specific event. This works because the component takes ownership of all sub-events and actions related to this event. If another component needs to push or pull anything, there should be an official process on both sides to handle it. Control is specifically delegated.</p><h4>Config Objects</h4><p>True to Functional Reactive ways of thinking, a config object should be pushed into the component. The component should require this object. The component uses it to drive all of its functions. Config Objects provide the necessary nutrition for optimal performance. They also allow the component to be used in any project simply by declaring parameters.</p><pre>const config = {<br>  one: &#39;value&#39;,<br>  two: { complexData },<br>  three: () =&gt; functions()<br>}</pre><pre>const Component = (config) =&gt; {<br>  if (!config) throw new Error(&#39;Because reasons.&#39;)</pre><pre>// config can be used as desired<br>  const { one, two, three } = config</pre><pre>return {<br>    one,<br>    two,<br>    three,<br>  }<br>}</pre><p>asdf</p><h4>External Side Effects</h4><p>Simple, the root level of the component should not modify any external state. There is a permission boundary. These potential side effects occur when the component freely mutates parent state. There should be no reaching into other files and grabbing things. With respect to the Config Object, any required data should probably be pushed into the component. The component could also pull the necessary data in. This would be like a hook that allows the component to ask for state.</p><p><strong>Here is a naive button; it could participate in any event:</strong></p><pre>const Component = (config) =&gt; {<br>  const { onEvent, text, css } = config</pre><pre>return (<br>    &lt;button onClick={onEvent} style={css}&gt;<br>      {text}<br>    &lt;/button&gt;<br>  )<br>}</pre><p>In this above example, the Component says, “the first one to handle this event wins”. Some function in the parent scope handles both the response action and the text for the button. All this component actually does is provide a framework for making responses to Button pressing. Side Effects are critically required for this to work.</p><p>Side Effects are theoretically bad because they break referential transparency. Imagine you had a function called <strong>addTogether(1, 2)</strong> which always returns 3 but also changes the color of a background to blue. If someone didn’t know the background turned blue, they would be missing that secret knowledge that may only be known by observing a single line of code hidden somewhere.</p><p>Functional Reactive way of thinking would have us be aware of the propagation of change, and we would ensure there is an official process in the component to handle this. Not doing so is analogous to shady black market deals.</p><p>Here is an example of</p><p>asdf</p><h3>JSX</h3><p>I won’t leave you empty handed about JSX after reading all that. My thoughts can be summarized by this quote from Mark Dalgleish:</p><blockquote>“What’s interesting, though, is that rendering to the DOM is not part of the core React library, instead being provided by <em>react-dom.</em></blockquote><pre>import { render } from <strong>&#39;react-dom&#39;</strong></pre><blockquote>Even though React was built for the DOM first, and still gets most of its usage in that environment, this model allows React to target wildly different environments simply by introducing new renderers.</blockquote><blockquote>JSX isn’t just about virtual DOM — it’s about virtual <em>whatever.”</em></blockquote><p>Source: Mark Dalgleish (<a href="https://medium.com/seek-blog/a-unified-styling-language-d0c208de2660">https://medium.com/seek-blog/a-unified-styling-language-d0c208de2660</a>)</p><p>I’ll spare you the details about what JSX is. Mark captures why we care about it in the quote above. JSX represents something much bigger. In 2018, we are probably looking at the tip of the ice berg. I would encourage you to pay attention. JSX is just a notation. This custom renderer jazz is very important. I will leave it up to you to research further.</p><p>Remember, I do not seek to tell you exactly the right answer. I seek to show you some ways to reliably find the right answer. If you propose some changes, write an article. We can maintain a live reference to it from here. When you mutate it, I won’t have to update the live reference.</p><h3>Recommended Next Steps</h3><p>I recommend studying Neo4j because of relationships between data compared to relational databases. It is fundamentally different and a profound upgrade in some ways. I am a great fan of the unstructured data that fits nicely into algorithms and reveals vectors and intensity values.</p><p>If you disagree, that’s not my problem. If you agree, study related data because this free flowing, unstructured data type is a magical companion to Functional Reactive Programming. It’s kind of why GraphQL exists; because Facebook required to communicate with the Social Graph. That is only one type of graph. If that doesn’t blow your mind, then you are probably already sufficiently advanced at some concepts of your choosing.</p><p>This article will finish rendering at the next character in this sentence chain.</p><h4>LET THESE PEOPLE KNOW</h4><p>@mate0day</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=521ea9f57d30" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[React’s setState is a special function, and it helps with asynchronous concurrency]]></title>
            <link>https://agm1984.medium.com/reacts-setstate-is-a-special-function-and-it-helps-with-asynchronous-concurrency-669eddbe3dd1?source=rss-62ac59fdc132------2</link>
            <guid isPermaLink="false">https://medium.com/p/669eddbe3dd1</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[react-native]]></category>
            <dc:creator><![CDATA[Adam Mackintosh]]></dc:creator>
            <pubDate>Sat, 14 Jul 2018 18:06:25 GMT</pubDate>
            <atom:updated>2018-07-17T01:43:51.366Z</atom:updated>
            <content:encoded><![CDATA[<p>So how do we use it properly?</p><p>Let’s investigate this code example here:</p><pre>componentDidMount() {<br>  fetch(&#39;http://example.com/rss.xml&#39;)<br>    .then((response) =&gt; response.text())<br>    .then((response) =&gt; {<br>      parseString(response, function (err, result) {<br>        this.setState({<br>          articles: JSON.stringify(result.rss.channel[0].item)<br>        })<br>        console.log(&#39;RAW: &#39;  + result.rss.channel[0].item);<br>        console.log(&#39;THIS: &#39; + this.state.articles);<br>      });<br>    });<br>}</pre><p>First, notice the code is in the componentDidMount() lifecycle method. The component was just born, and now it is making a fetch() call to get some data from a server.</p><blockquote><strong>Bonus Note</strong>: Notice how it is shown in componentDidMount and not componentWillMount. This is because network calls should be made here. If you make a network call in componentWillMount, there is a chance you could receive the data before the component is fully mounted. At which point this.setState() wouldn’t work because there is no component on which to set.</blockquote><p>The important thing to note is that once the data is acquired, it is set into the component’s state via this.setState({ articles }).</p><p>In React, setState is asynchronous, so the code on the following line after setState (the two console.log()s) will be executed <strong>immediately </strong>after the setState call is placed in the event loop. This is a problem.</p><p>The above code is flawed because those two console.logs are being executed before setState has completed. Great, now we’re screwed. Well actually, it’s fine.</p><p>If you want to read closer about this moment in time of setState, check out the top answer here:</p><p><a href="https://stackoverflow.com/questions/36085726/why-is-setstate-in-reactjs-async-instead-of-sync">Why is setState in reactjs Async instead of Sync?</a></p><p>It doesn’t go into hyper-fine grain detail, but that’s ok. If you are at the point where you want to know exactly, you should scour the React documentation here:</p><p><a href="https://reactjs.org/docs/faq-state.html">Component State - React</a></p><h4>setState Callback</h4><p>The secret trick here is that setState accepts a second parameter which is a callback that will be executed after the state is updated. You could place all your following logic inside that statement.</p><p>Here is a sampler pack:</p><pre>this.setState({ dogs: 350 }, () =&gt; { console.log(&#39;The state has been updated.&#39;) })</pre><blockquote><em>The second parameter to </em><em>this.setState() is an optional callback function that will be executed once setState is completed and the component is re-rendered. Generally we recommend using componentDidUpdate() for such logic instead.</em></blockquote><blockquote>Cite<em>: </em><a href="https://reactjs.org/docs/react-component.html"><em>https://reactjs.org/docs/react-component.html</em></a></blockquote><p>Notice how it says ‘once setState is completed’. Another way to state that is to say, once the state change has been resolved. It implies a formal change process and definitely not a synchronous function doing one setoperation.</p><p>Let’s say for a second you had several components in React and each one calls this.setState() at the same time. You would probably consider it very important to know the exact order those calls were made if they were all incrementing the same state variable.</p><p>React can batch and reconcile those crazy situations for you and help maximize performance. The important thing is FIFO (first in, first out). React is considering your state changes with respect to time.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/205/1*aIPYJ11-bIX6gkAl-hRgfw.png" /><figcaption>Fig 1.X — Cite: <a href="https://www.12manage.com/description_fifo.html">https://www.12manage.com/description_fifo.html</a></figcaption></figure><p>Back to our first example code at the top, it could look like this:</p><pre>componentDidMount() {<br>    fetch(&#39;http://example.com/rss.xml&#39;)<br>        .then((response) =&gt; response.text())<br>        .then((response) =&gt; parseString(response, (err, result) =&gt;<br>            this.setState({<br>                articles: JSON.stringify(result.rss.channel[0].item),<br>            }, () =&gt; {<br>                console.log(&#39;RAW:&#39;, result.rss.channel[0].item)<br>                console.log(&#39;THIS:&#39;, this.state.articles)<br>            }));<br>        );<br>}</pre><p>Basically React is doing some wizard techniques behind the scenes to ensure your <strong>state integrity</strong> is maintained when you want to see what the state is after the change is complete.</p><p>I can see why such complexity seems a bit bulky, but the process is not intended to be as simple as possible. this.setState() is intended to provide a formal change management process because state is the most important thing at the moment of change. Outcomes depend on order of operations, otherwise math doesn’t work, and you see bugs and poor UX.</p><p>Check out the modification I did on the console.log:</p><pre>// before<br>console.log(&#39;THIS: &#39; + this.state.articles);</pre><pre>// after<br>console.log(&#39;THIS:&#39;, this.state.articles);</pre><p>It too can accept multiple parameters.</p><h4>Asynchronous Concurrency</h4><p>Read this definition for console.log() and multiple parameters.</p><blockquote><em>[</em>Console.log accepts: a<em>] list of JavaScript objects to output. The string representations of each of these objects are appended together in the order listed and output. Please be warned that if you log objects in the latest versions of Chrome and Firefox what you get logged on the console is a reference to the object, which is not necessarily the ‘value’ of the object at the moment in time you call console.log(), but it is the value of the object at the moment you click it open.</em></blockquote><blockquote>Cite<em>: </em><a href="https://developer.mozilla.org/en-US/docs/Web/API/Console/log"><em>https://developer.mozilla.org/en-US/docs/Web/API/Console/log</em></a></blockquote><p>This definition is incredibly important because it means what you see in your Dev Tools console as output from console.log() does not necessarily reflect exactly how the Objects looked at the moment they were logged. Live references are the reason, meaning pass by reference not pass by value. A good way to facilitate that (which is related to time travel debugging FYI) is to use immutable Functional Programming techniques. You have to make copies. Copies are basically snapshots with respect to time, so you can benefit from using ways of thinking related to Calculus, or the study of continuous motion. Of what? Data flow with respect to time.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/959/1*z9Xl0-QbWzsMJt63qq9gLA.png" /><figcaption>Fig 1.0 — Cite: <a href="http://msl-network.readthedocs.io/en/latest/concurrency_async.html">http://msl-network.readthedocs.io/en/latest/concurrency_async.html</a></figcaption></figure><p>this.setState() is a helper that only gets in your way enough to help promote state integrity and efficient data flow. When? During asynchronous concurrency centered around data flow while not losing track of any data. Economics depends on it.</p><p>I like that console.log() definition additionally because it speaks to the asynchronous nature of live references. One function by itself can be synchronous, but due to the callstack and function queue, you can load up an infinite number of functions into the queue and they will complete in a random order based on how long each one takes to complete because only one function passes through the callstack at a time, on the main thread.</p><p>Of course, it seems random order to us, but it’s actually the mathematically-exact fastest path through all those functions, assuming they are all deterministic.</p><p>Fast forward to our fetch() example, setState doesn’t care to stop surrounding code from executing or wait for surrounding code unless you explicitly tell it to. That’s what the callback is for, if you need to run some bonus code.</p><h4>Functional setState</h4><p>While we are talking about setState, I should mention also that you can pass a function to it. Imagine that the second parameter callback is your method of looking into the future after setState. The opposite of that is looking into the past, which is where the functional setState comes in handy by giving you closure around the previous unit of time. The previous state also happens to be the current state of whatever you are updating.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/470/1*qsUQ9gCPd454N8dBVi1HkA.png" /><figcaption>Fig 1.1 — Cite: <a href="https://shift.infinite.red/react-conf-2017-day-1-a-review-7cbf4ec3af3c">https://shift.infinite.red/react-conf-2017-day-1-a-review-7cbf4ec3af3c</a></figcaption></figure><p>Functional setState is great because you are guaranteed first in, first out in the order functions are called. You should research that further. You may find this article here particularly revealing:</p><p><a href="https://medium.freecodecamp.org/functional-setstate-is-the-future-of-react-374f30401b6b">Functional setState is the future of React</a></p><p>Here is a sampler pack for that:</p><pre>this.setState((prevState) =&gt; {<br>    // hello I like cats.gif<br>    // we could run some fascinating code here<br>    // as long as we return an object<br>    console.log(&#39;rad&#39;)</pre><pre>    return {<br>        articles: [ ...prevState.articles, { new: 1, article: true }],<br>    }<br>})</pre><p>Functional setState gives you a safe window to guarantee state integrity through your update. I showed that example as spreading an Array into a new Array and appending it with an object to demonstrate a real scenario where you might need to refer to the current state as part of your setState operation.</p><p>In a real scenario, you might sharpen that above code to this, which capitalizes on implicit return of an Object literal (requires fat arrow syntax):</p><pre>this.setState(prevState =&gt; ({<br>    articles: [ ...prevState.articles, { new: 1, article: true }],<br>})</pre><p>Hopefully that helps us see the climate of what is happening. In React, it is important to undergo a formal change management process, so every time you are getting or setting data, you need to be careful <strong>who </strong>is reading or writing data and from <strong>where</strong>, like which functions and which part of your application.</p><blockquote>React’s way of taming JavaScript is to promote data to flow unidirectionally, immutably, and deterministic.</blockquote><h4>Reactive Programming</h4><p>It makes things easier to reason about if everything is flowing one way. That only works if you require immutability and prefer a deterministic system. It means most functions are written declaratively, so they declare what the state looks like at the start of a function, do stuff, then declare what the state is at the end of the function.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/742/1*LxrbGIvMvvr494R-60apWA.png" /><figcaption>Fig !.2 — Cite: <a href="https://dzone.com/articles/5-things-to-know-about-reactive-programming">https://dzone.com/articles/5-things-to-know-about-reactive-programming</a></figcaption></figure><p>React makes you think you are writing mostly pure JavaScript, but really it is managing your state using a first in, first out technique to avoid race conditions when perhaps thousands of components are trying to write to the state at the same time. All while the user is in the browser rolling their face across the keyboard triggering all kinds of events.</p><p>We must not block the main thread or else suffer poor UX. It’s important we circle back on that idea because mostly what we are talking about today is <strong>how</strong>. It’s more important <strong>what</strong> we are doing — trying to maximize efficiency of managing actions and events while maintaining the app’s state integrity.</p><p>Imagine you had a calculator, like the one you used in school, and it randomly gave you the incorrect answer. Not only is that a pretty garbage calculator but also it lost control over its state. The calculator only had one job. React is doing that job for you, and setState helps.</p><p>A formal change management process means there is probably an official pattern that you should use every time you get or set data. Luckily, the patterns are usually what you would do if you were writing pure JavaScript. Reactive Programming, Functional Programming, and immutability can help tame the wild asynchronous parallel concurrency gods. If you haven’t came across the word semaphore yet, then you should read this definition:</p><p><a href="https://en.wikipedia.org/wiki/Semaphore_(programming)">Semaphore (programming) - Wikipedia</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*O8L5BxOGgmkqj50a7KfMNA.png" /><figcaption>Fig 1.3 — Cite: <a href="http://micro-os-plus.github.io/user-manual/semaphores/">http://micro-os-plus.github.io/user-manual/semaphores/</a></figcaption></figure><p>Reading the definition of ACID Transactions can be beneficial as well:</p><p><a href="https://en.wikipedia.org/wiki/ACID">ACID - Wikipedia</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/375/1*V8gwuykKriGt7J9hj6AdLg.gif" /><figcaption>Fig 1.4 — Transaction commit or rollback</figcaption></figure><p>A transaction is like a state change. In fact, I’m pretty sure it is exactly a state change. For example, completing the transaction of giving someone $3.50 has an affect on this.state.yourWallet and this.state.theirWallet. Sometimes databases lock over the period of a transaction. It’s called awrite-lock. This creates a situation where state changes are getting backed up. This is called dead-lock. You want to stay away from deadlock.</p><p>The nice thing is, immutable Functional JavaScript is fairly ideally-suited to handle the continuous motion of data flow. It’s single threaded, but it’s also replicable. A cluster of JavaScript nodes is an extremely beautiful thing to examine. It would look like a recurrent <strong>directed acyclic graph</strong>. That is to say, it would look like a directed acyclic graph that can be fed back into itself. If that’s not mind blowing, I don’t know what is.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/260/1*606YwvAtdzf1qvhgB7OJEg.png" /><figcaption>Fig 1.5 — DAG with Transitive Closure</figcaption></figure><p>Note about DAGs:</p><blockquote>Adding the red edges to the blue directed acyclic graph produces another DAG, the <a href="https://en.wikipedia.org/wiki/Transitive_closure">transitive closure</a> of the blue graph. For each red or blue edge <em>uv</em>, <em>v</em> is <a href="https://en.wikipedia.org/wiki/Reachability">reachable</a> from <em>u</em>: there exists a blue path starting at <em>u</em> and ending at <em>v</em>.</blockquote><blockquote><em>Cite</em>: <a href="https://en.wikipedia.org/wiki/Directed_acyclic_graph">https://en.wikipedia.org/wiki/Directed_acyclic_graph</a></blockquote><p>DAGs are related to function composition, because a function has a discrete start and discrete end, so it is directed, and it does not loop back to itself, so it it unidirectional. Acyclic means “not cyclic” which means “not occurring in cycles” which means “not circular” which means “straight line”.</p><p>A deterministic chain of functions is a directed acyclic graph because each function can bifurcate which creates a giant tree but it does not loop back into it self, so it allows you to maintain a deterministic movement when you use recursion, meaning it still always outputs the same thing if you put in the same thing.</p><p>In a DAG, you do not go backwards but you may pass through recursive functions. I’ve never seen anyone talk about this stuff, but it reminds me of Mathematics, so I describe it this way. Imagine a fractal.</p><p>My DAG mentions are not directly related to this.setState(), but they are indirectly related because most React apps are DAGs. They have a root component, and data passes from there to be rendered on your screen and may enter your app somewhere downstream.</p><p>We also recall that data typically flows unidirectionally and this gives rise to the React framework’s setState method because it is designed to facilitate first in, first out processing and reliable order of operations.</p><p>As such, when you want to set a component’s state, it’s really an event. You are passing that event either a function or a plain old JavaScript Object (POJO), and you can additionally supply a callback function if you want. It will be processed after.</p><h3><em>TLDR</em></h3><p>It’s very important what you are doing before, during, and after this.setState(). It&#39;s a special function, a class method on the Component Class. I hope I have helped us understand a couple of its secrets today.</p><p>Our fetch() example was seeking to perform two operations in one setState call. Normally, you only do one which is to set the state ☺. Normally, other components are listening for changes, so setState callback is a bit more imperative than it is declarative; however, sometimes it is useful. Using setState’s callback does nest one additional dimension, but it’s fine because we are just performing one more operation, or a couple quick ones. <strong>I wouldn’t recommend it if you want a chain of functions in the callback.</strong></p><p>Notice the React documentation that states,</p><blockquote><em>Generally we recommend using componentDidUpdate() for such logic instead.</em></blockquote><p>The reason it says that is componentDidUpdate() is listening for state changes, so you can run logic there that is listening for certain conditions and then acting upon those changes. It saves you from having to care about performing a second operation after setState at the call site (ie: where in the code you called this.setState()).</p><p>Imagine you did this instead for our fetch() example:</p><pre>componentDidMount() {<br>    fetch(&#39;http://example.com/rss.xml&#39;)<br>        .then((response) =&gt; response.text())<br>        .then((response) =&gt; parseString(response, (err, res) =&gt;<br>            this.setState({<br>                articles: JSON.stringify(res.rss.channel[0].item),<br>                hasFetchedStuff: true,<br>            })<br>        ));<br>}</pre><p>Check out that hasFetchedStuff piece. That could lead to something like this in componentDidUpdate():</p><pre>componentDidUpdate() {<br>    if (this.state.hasFetchedStuff) {<br>        this.triggerSomething()<br>    }<br>}</pre><p>That can free your componentDidMount from having to care about anything after getting the data, which is perhaps good decoupling and a nice separation of concerns.</p><p>It’s also more reactive-like because:</p><ul><li>when the mount event occurs, do this</li><li>when the data is acquired, do this</li></ul><p>Later, you can freely change how the data is acquired or what you do with it just by manipulating those hook points. The start of a function always presents a window of opportunity to see what it is allowed to, and the end of a function always presents an opportunity to see what was happening at that moment in time somewhere in the application.</p><p>I wrote this originally as an answer on StackOverflow, but I realized it was kind of long and should be an article in itself.</p><p>You could follow me on Twitter. I use it to render key thoughts:</p><p><a href="https://www.twitter.com/agm1984"></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=669eddbe3dd1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to set up ES Lint for Airbnb, Vue JS, and VS Code]]></title>
            <link>https://agm1984.medium.com/how-to-set-up-es-lint-for-airbnb-vue-js-and-vs-code-a5ef5ac671e8?source=rss-62ac59fdc132------2</link>
            <guid isPermaLink="false">https://medium.com/p/a5ef5ac671e8</guid>
            <category><![CDATA[eslint]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[vuejs]]></category>
            <dc:creator><![CDATA[Adam Mackintosh]]></dc:creator>
            <pubDate>Thu, 14 Jun 2018 17:55:01 GMT</pubDate>
            <atom:updated>2020-04-05T19:26:11.882Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/971/1*loAr6t7a4T901XKl0NVugA.png" /><figcaption>Fig 1.0 — ES Lint, the handy harassment helper</figcaption></figure><p>Greetings human code-scavenger. Today, I will show you how to get ES Lint working with Vue JS. If you are using Laravel to some degree, your environment will probably be ready to go for these instructions. If you are using vue-cli, your needs may be different, but you should still see some tasty nugget-like information.</p><p>I will refine these steps over time as I ram my head into the keyboard more. Please help me in the comments section below if you have a note I should be aware of.</p><p><strong>Edit 1: </strong>Today (April 2, 2020) I edited the bottom of this article. Please skim the entire article before taking your first action because I edited my config to remove babel-eslint.</p><p><strong>Edit 2:</strong> Today (April 5, 2020) I noticed ES Lint was throwing a parser error related to dynamic importing. The fix was simple, and it means babel-eslint parser isn’t required unless you are using dynamic imports, in which case babel-eslint parser <strong>is required</strong>.</p><h3>First, install these packages</h3><p>Since we are using VS Code today, we will just open the Integrated Terminal. Open that.</p><p>Now type:</p><pre>$ npm install --save-dev babel-eslint<br>$ npm install --save-dev eslint<br>$ npm install --save-dev eslint-config-airbnb-base<br>$ npm install --save-dev eslint-plugin-import<br>$ npm install --save-dev eslint-plugin-vue</pre><pre>// Pro-style efficient<br>$ npm install --save-dev babel-eslint eslint eslint-config-airbnb-base eslint-plugin-import eslint-plugin-vue</pre><ul><li>babel-eslint: this is needed for parserOptions. It is a logical backbone for ES Lint to stand on. It’s utilized slightly different than React, so pay attention in this article.</li><li>eslint: this is the main ES Lint package.</li><li>eslint-config-airbnb-base: this is what brings us the Airbnb nectar settings. Take careful note that we are <strong>not</strong> using eslint-config-airbnb. That would install the package designed to be used with React. If you installed that, VS Code and ES Lint will get hella mad about JSX plugins.</li><li>eslint-plugin-import: this is required for airbnb-base. Read their docs for more info. Basically, it allows ES Lint to get angry about your import statements.</li><li>eslint-plugin-vue: this is a nectar plugin that allows you to win.</li></ul><blockquote>Deprecated: eslint-plugin-html</blockquote><p>eslint-plugin-html is deprecated in favor of eslint-plugin-vue.</p><p>See: <a href="https://github.com/BenoitZugmeyer/eslint-plugin-html/issues/68">https://github.com/BenoitZugmeyer/eslint-plugin-html/issues/68</a></p><h3>Second, use these config settings</h3><p>Now that we installed that crap, we can create a file in the root directory.</p><ul><li>Create ./.eslintrc.json</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/71ba2e460f3fd3b2300e70b7230dce02/href">https://medium.com/media/71ba2e460f3fd3b2300e70b7230dce02/href</a></iframe><h4>babel-eslint</h4><p>Here is how React uses babel-eslint:</p><pre>&quot;parser&quot;: &quot;babel-eslint&quot;</pre><p>Here is how Vue uses it:</p><pre>&quot;parserOptions&quot;: {<br>    &quot;parser&quot;: &quot;babel-eslint&quot;<br>},</pre><blockquote><strong>More info</strong>: read here <a href="https://github.com/vuejs/eslint-plugin-vue/issues/186">https://github.com/vuejs/eslint-plugin-vue/issues/186</a></blockquote><h4>Airbnb</h4><p>Here is how React uses Airbnb:</p><pre>&quot;extends&quot;: &quot;airbnb&quot;</pre><p>Here is how Vue uses Airbnb:</p><pre>&quot;extends&quot;: [<br>    &quot;airbnb-base&quot;,<br>    &quot;plugin:vue/recommended&quot;<br>],</pre><p>That anchors in eslint-plugin-vue.</p><h4>Kick Start</h4><p>After installing all that garbage, I generally recommend the following three steps to be completed synchronously as a method of drop kicking ES Lint into gear:</p><p>I forgot to mention that I usually have ES Lint installed globally:</p><pre>sudo npm install -g eslint --save</pre><ol><li>Grab./.eslintrc.json file contents to clipboard, some may recall this as left mouse-click and CTRL+AC combo from Mortal Kombat.</li><li>Execute $ eslint --init in the Integrated Terminal.</li><li>Conform to the demands of the script.</li></ol><p><strong>Note</strong>: you may need to close one or all of your currently open <em>.vue</em> files, or in some extreme operating system warzone conditions, you may need to restart VS Code.</p><blockquote><em>eslint --init</em> is a great command to memorize and always run it when ES Lint gets mangled. Doing so can release hints toward a potential problem. Sometimes I forget a package or two and it detonates real good with explicit errors.</blockquote><p>EDIT: I forgot there is actually a step 4, which is to paste those clipboard contents back into the .eslintrc.json file because it gets overwritten when you run eslint --init. No big deal, just paste it back over top.</p><h3>Third, secret VS Code settings</h3><p>In VS Code now, go to <strong>File </strong>&gt; <strong>Preferences </strong>&gt; <strong>Settings </strong>and add this to your user settings JSON file:</p><pre>&quot;eslint.validate&quot;: [<br>    &quot;javascript&quot;,<br>    &quot;javascriptreact&quot;,<br>    {<br>        &quot;language&quot;: &quot;vue&quot;,<br>        &quot;autoFix&quot;: false<br>    }<br>],</pre><blockquote><strong>Note</strong>: you can turn on autoFix if you’re crazy.</blockquote><h4>Wait</h4><p>If you get a message from VS Code that says “eslint.validate” is an unknown configuration setting, then you need to install Dirk Baumer’s ES Lint extension.</p><p>Visit: <a href="https://marketplace.visualstudio.com/items?itemName=dbaeumer.vscode-eslint">https://marketplace.visualstudio.com/items?itemName=dbaeumer.vscode-eslint</a></p><p>While we’re downloading extensions, I highly recommend this one here called <strong>eslint-disable-snippets</strong>:</p><p><a href="https://marketplace.visualstudio.com/items?itemName=drKnoxy.eslint-disable-snippets">eslint-disable-snippets - Visual Studio Marketplace</a></p><p>With it, you can be at or above a line you want to disable, and start typing “eslint-disable” and usually VS Code’s auto-complete suggestions will kick up after you type even just “esl”, so it’s rad. I personally always forget the syntax, so the extension is a welcome 24/7 helper.</p><h3>Fourth, probably install Vetur Extension</h3><p>I’m pretty sure you need this also. This should actually be step 1 or your Vue files will have no syntax highlighting. You probably already have it, but just in case:</p><h4>Vetur extension by Pine Wu</h4><p>Visit: <a href="https://marketplace.visualstudio.com/items?itemName=octref.vetur">https://marketplace.visualstudio.com/items?itemName=octref.vetur</a></p><p>Follow these simple steps here:</p><ol><li>Install that banshee</li><li>Process complete</li></ol><h4>*** Windows Users ***</h4><p>Windows users may encounter issues if they installed Vetur without elevated system privileges. I think this is because it does some kind of secret wizardry in your user profile, etc. You will need elevated privileges to install everything successfully.</p><p>If you are running Windows, do this. If you didn’t install Vetur yet, omit step 1 to 3:</p><ol><li>Goto VS Code extensions</li><li>Uninstall Vetur</li><li>Hit the Reload button</li><li>Close VS Code</li><li>Right click VS Code icon in the Task Bar</li><li>Select Run as Administrator</li><li>Goto VS Code extensions</li><li>Install Vetur</li><li>Hit the Reload button</li></ol><p>Everything should be working for you now.</p><h3>Conclusion</h3><p>Finally, we are done. I bid you good luck on your coding journeys, and I am excited for the harassment you will get from ES Lint.</p><h4>Helpful URLs</h4><ul><li><a href="https://vuejs.github.io/vetur/setup.html">https://vuejs.github.io/vetur/setup.html</a></li><li><a href="https://codeburst.io/tutorial-how-to-add-eslint-to-your-vue-js-project-ccfb84fab9">https://codeburst.io/tutorial-how-to-add-eslint-to-your-vue-js-project-ccfb84fab9</a></li><li><a href="https://alligator.io/vuejs/vue-eslint-plugin/">https://alligator.io/vuejs/vue-eslint-plugin/</a></li><li><a href="https://github.com/vuejs/vetur/issues/660">https://github.com/vuejs/vetur/issues/660</a></li></ul><h3>Bonus edit</h3><p>With the newest versions of ES Lint, and any other upstream or downstream logic, such as VS Code core, I find I require a little different config now — in April 2020:</p><p><strong>package.json</strong></p><pre>&quot;devDependencies&quot;: {<br>    &quot;eslint&quot;: &quot;^6.8.0&quot;,<br>    &quot;eslint-config-airbnb-base&quot;: &quot;^14.1.0&quot;,<br>    &quot;eslint-plugin-import&quot;: &quot;^2.20.2&quot;,<br>    &quot;eslint-plugin-vue&quot;: &quot;^6.2.2&quot;,<br>}</pre><ul><li>babel-eslint: if you are using dynamic imports for bundle splitting, add:</li></ul><pre>    &quot;babel-eslint&quot;: &quot;^10.1.0&quot;,</pre><p><strong>.eslintrc.json</strong></p><pre>{<br>    &quot;env&quot;: {<br>        &quot;browser&quot;: true,<br>        &quot;es6&quot;: true,<br>        &quot;node&quot;: true<br>    },<br>    &quot;extends&quot;: [<br>        &quot;eslint:recommended&quot;,<br>        &quot;airbnb-base&quot;,<br>        &quot;plugin:vue/essential&quot;<br>    ],<br>    &quot;globals&quot;: {<br>        &quot;Atomics&quot;: &quot;readonly&quot;,<br>        &quot;SharedArrayBuffer&quot;: &quot;readonly&quot;<br>    },<br>    &quot;parserOptions&quot;: {<br>        &quot;ecmaVersion&quot;: 2019,<br>        &quot;sourceType&quot;: &quot;module&quot;<br>    },<br>    &quot;plugins&quot;: [<br>         &quot;vue&quot;<br>    ],<br>    &quot;rules&quot;: {<br>        // yolo    <br>    },<br>}</pre><ul><li>babel-eslint is required for dynamic importing — plugin: @babel/plugin-syntax-dynamic-import). Note: adding/removing the babel-eslint parser takes affect immediately. Add a character to a file, remove it, press CTRL+S, and you’ll see immediately if the parser is installed correctly.</li></ul><pre>&quot;parserOptions&quot;: {<br>    &quot;parser&quot;: &quot;babel-eslint&quot;,<br>    &quot;ecmaVersion&quot;: 2019,<br>    &quot;sourceType&quot;: &quot;module&quot;<br>},</pre><ul><li>extends eslint:recommended seems required too; I’m not 100% sure about this, but I was having trouble linting .vue files for stuff like requiring semi-colon, so some rules might not be included in the airbnb-base, and rather, maybe the Airbnb set is extended from the eslint set.</li></ul><p><strong>VS Code settings.json</strong></p><ul><li>Code &gt; Preferences &gt; Settings (OSX)</li><li>File &gt; Preferences &gt; Settings (Probably on Windows)</li></ul><pre>&quot;eslint.options&quot;: {<br>    &quot;extensions&quot;: [&quot;.html&quot;, &quot;.js&quot;, &quot;.vue&quot;, &quot;.jsx&quot;]<br>},<br>&quot;eslint.validate&quot;: [<br>    &quot;javascript&quot;,<br>    &quot;javascriptreact&quot;,<br>    &quot;html&quot;,<br>    &quot;vue&quot;<br>],</pre><ul><li>After reading some GitHub issues threads, I added those above VS Code settings.</li><li>Just add the React ones in there, yolo-style; it may help you one day to forget about those but already have them when “the day” comes.</li><li>You can use JSX in Vue (ie: @vue/babel-plugin-transform-vue-jsx) so you may find yourself linting that in functional components that use JSX syntax.</li><li>VS Code itself was throwing an error with that autoFix: true stuff, and it told me to use the “string form”, which is what you see above. If you happen to see that, you aren’t crazy. I saw it too, and I yolo’d past it — no harm so far.</li></ul><h3>A note about Airbnb-base</h3><p>Please note that if you choose to roll with airbnb-base , you should tend to prefer its recommendations rather than turning those rules off. <strong>My best tip for anyone is to always Google a rule that you aren’t familiar with</strong>, and read enough articles and docs (especially GitHub issues threads involving questions from people and answers from Airbnb team).</p><p>In many cases, you will find the answer to “why do I need this garbage?” leads towards JavaScript danger zones, memory allocation, and functional composability (and therefore, readability and clarity of Functional Programming (FP) styles).</p><p>In my experience, reading these discussions and studying FP has lead me to emphatically endorse the airbnb-base ruleset, and to generally feel comfortable seeing people disable specific rules for specific purposes. If you understand the rule and disagree with it, turn off that rule. Doing so places an explicit mention in your ES Lint config file. That’s all a person needs.</p><h3>Final thing, Webpack aliases</h3><p>Is your life currently ruined by something like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/792/1*cw_r8DuscCqJuOfHP2ZpuA.png" /><figcaption>Fig 3.0 — Aliases, legal yet illegal</figcaption></figure><p>Install:</p><pre>npm install --save-dev eslint-import-resolver-alias</pre><p><strong>Laravel-mix (aka Webpack config)</strong></p><pre>mix.webpackConfig({<br>    resolve: {<br>        extensions: [&#39;.js&#39;, &#39;.vue&#39;],<br>        alias: {<br>            &#39;@&#39;: `${__dirname}/resources`,<br>        },<br>    },<br>});</pre><ul><li>Note the resolve key there if you are using something <em>ultra-wild</em> like “just Webpack by itself and not Laravel Mix”; there will be a standard deviation of syntax.</li></ul><p><strong>.eslintrc.json</strong></p><pre>&quot;settings&quot;: {<br>    &quot;import/resolver&quot;: {<br>        &quot;alias&quot;: {<br>            &quot;map&quot;: [<br>                [&quot;@&quot;, &quot;./resources&quot;]<br>            ],<br>            &quot;extensions&quot;: [&quot;.js&quot;, &quot;.vue&quot;]<br>        }<br>    }<br>}</pre><p>source: <a href="https://github.com/benmosher/eslint-plugin-import/issues/496">https://github.com/benmosher/eslint-plugin-import/issues/496</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a5ef5ac671e8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[An intro to Functional Programming in JavaScript~ (and React and/or Vue)]]></title>
            <link>https://agm1984.medium.com/an-overview-of-functional-programming-in-javascript-and-react-part-one-10d75b509e9e?source=rss-62ac59fdc132------2</link>
            <guid isPermaLink="false">https://medium.com/p/10d75b509e9e</guid>
            <category><![CDATA[functional-programming]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[immutability]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Adam Mackintosh]]></dc:creator>
            <pubDate>Fri, 18 May 2018 00:07:04 GMT</pubDate>
            <atom:updated>2020-10-05T20:55:19.443Z</atom:updated>
            <content:encoded><![CDATA[<p>This article is worth your retinal zoom-in time, but remember that good is subjective to the observer. This is about Functional Programming and data flow over time. This article is for people that haven’t looked that close at Functional Programming yet—or for those whom wish to build intuition about how to approach data flow through apps.</p><blockquote><strong>Bonus Note:</strong> patterns described here should be applicable in React, Vue, Angular, and really any other programming language where the main focus is data or a user — while actions and events are involved. Imagine for a moment, if something is going from somewhere-to-somewhere, we can start to sample ideas from Mathematics and Physics. We can create well-characterized patterns to solve well-characterized scenarios, and we can also discover interesting patterns.</blockquote><p>The most important take away from this article is that immutability and maintenance of the integrity of your application’s state are among the most important, and those ideas will lead you to effective function composition.</p><blockquote>Functions can act as labels… labels of function throughout your application. Sometimes people label too much and create a lot of granular functions. It is important to note that the inlet and outlet of each function represent a jump in dimension. <strong>Abstraction can cause confusion when paired with granularity because you might be comparing two functions not directly connected together; you also lose some freedom of access to local data if you move upstream.</strong></blockquote><p>I will show you an image of what it looks like to observe 3 dimensions at the same time:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/298/1*eLKZ-joM4whp7UzEuYPpyw.jpeg" /><figcaption>Fig 1.0 — Dimensions</figcaption></figure><p>For example, imagine some data started at the left-most dot and then traveled through the middle square towards the largest square. It’s like a flow of information over time. The dot is upstream of the middle square, and the largest square is downstream of the middle square.</p><p>The interesting part here is what happens at each dimension change. That’s the place where one function ends and another one starts:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/975/1*Q1nHWXWP8-bMxObX1XunKQ.png" /><figcaption>Fig 1.1 — Some kind of inter-dimensional movement</figcaption></figure><p>You already know this inter-dimensional movement quite well. It’s the relationship between grandparent to parent to child to grandchild. The parent has control of the child because it is upstream. This is abstraction.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/644/1*7ahgQ4U86Badq9ygdMDw6A.png" /><figcaption>Fig 1.3 — Waterslides with data as humans</figcaption></figure><p>Abstraction can be confusing for the same reason comparing two sections of water-slide pipe can be confusing if you want to confirm that they came from the same waterslide. Imagine looking at two random pieces of blue pipe that look the same. Where did they come from? Hopefully you knew, or hopefully you can see ID numbers on them. The interesting thing is that this ambiguity can spawn utility — sections can be composed. If you had a function that inputs a name and outputs the name withfont-weight: bold added to it, you can use that function anywhere, anytime you want to make something bold. You see the math in there too right?</p><blockquote>fn(name) = (name + bold)</blockquote><p>It’s kind of important that we stop for a moment and look directly at that = symbol. It means, at the moment in time we observed both sides of the equation at once, they were equal to each-other with infinite accuracy and precision. Notice the word at in my statement. I am describing a co-ordinate in space-time. I don’t really need to care where you are while you’re observing the equation. I can tell you with 100% certainty that they are equal at your current location at the moment in time you just looked at the =.</p><p>If you were a function, I could derive all kinds of information about your whereabouts and how you got there, and possibly where you are going. Math and Physics comes in so hard here because there are data flow vectors in play. If you were a baseball thrown at a known speed and angle from a known place at a known time, I could predict where and when you would be at very specific places.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/297/1*Zd7He4GbVwDk02d4oM4zUw.png" /><figcaption>Fig 1.4 — The slope of the tangent is 0 at the vertex</figcaption></figure><p>Maybe the throwing action can be a function, and you can calculate what to do with the baseball next at the moment in time it hits the ground, or someone in the back of the head. You might do something different depending which option it ends up being. You could split that throwing action into two functions: one that takes the baseball to the vertex, and one that takes the baseball to its final destination based on the amount of energy you supplied to the throwing process. 50% of the potential energy was used in each function. The point is there is an inter-dimensional-shift between each function, and that they are connected together. The outlet of the first function was equal = to the inlet of the second function at the moment in time they connected together. The flow of baseball is unidirectional.</p><p>In the image above the waterslides, you don’t have to care what’s in the previous or next dimension (waterslide pipe-section) as long as your green dots start with correct data and your orange dots end with the correct data. That’s what makes the = symbol true. In that font bold example, as long as your function always gets a name, you’re good. As long as the font always comes out bold, you’re good.</p><pre>const isBold = (name.bold === true);</pre><p>The above sampler pack there is a predicate meaning it only returns true or false, so it allows you to make a definition that works in any context to give you a yes/no answer about something at a particular moment in time. Predicates, and even predicate functions (a function that returns true or false), are extremely useful. We should always look to them first when our goal is to trap something down to a black or white response.</p><blockquote><strong>Predicates</strong>: we don’t want to care when it actually is true or false, we just want to set it up so that it will definitely change at the correct moment in time when some specific criterion(s) are true. This is a low-key form of decoupling things that matter from things that don’t matter.</blockquote><p>Imagine you’re some data flying through a function. You need to make a decision:</p><pre>const phoneNumberOfDavid = &#39;555-123-4576&#39;;</pre><pre>if (isBold) await call(phoneNumberOfDavid);</pre><p>Ok, now that’s done unless call() explodes. If David changed his phone number, that call function would still work, so who cares what it does as long as it works with your supplied data (radical hint: functions are labels). Notice how the code is written with respect to time as you are reading it, and that sounds Mathematicsy. Notice how there is a secret = inside that isBold variable, and a moment in time just came when you observed it.</p><blockquote>If functions always move downstream over time, you can write out on a piece of paper the series of functions (<strong>actions</strong> maybe) that kick off during an <strong>event</strong>, and you can quickly start to understand what you need to know to modify the series of functions. You can ask yourself: what data is involved, where is it coming from, where is it going to, and why?</blockquote><blockquote>There will be smaller details, but you need to establish the branches of a tree before you can draw leaves, unless you assemble the tree asynchronously, but you will always start and finish drawing the tree.</blockquote><p>Let’s bring it to a real example with some functions:</p><pre>import FibonacciAdapter from &#39;some-outlet-right-now&#39;;</pre><pre>const makeLeafOnBranch = (data) =&gt; {<br>    const scalingFactor = 1.618;</pre><pre>    return FibbonacciAdapter({<br>        action: &#39;ADD-LEAF&#39;,<br>        someRatio: scalingFactor,<br>        someData: data,<br>    });<br>};</pre><pre>const drawLeaf = data =&gt; makeLeafOnBranch(data);</pre><pre>const drawBranch = drawLeaf =&gt; drawLeaf();</pre><pre>drawBranch(data =&gt; drawLeaf(data));</pre><p>Pretty simple — if not a bit savage for something to just suddenly look at — we have a function whose job is to draw branches and another one to draw leaves, one at a time it sounds like. Notice how I labeled everything exactly what it’s doing using as little words as possible. I don’t say, “hey what’s (1+1)+2?” if I can say, “hey what’s 2+2?”.</p><p>The parent in this case is drawBranch. It has permission to call drawLeaf. If you are inside the drawBranch function, you are in a dimension before drawLeaf. In this case, drawLeaf needs to know the location of the branch or it can’t draw anything. We must expect that the branch location will be included when drawLeaf starts. Both of these functions possibly don’t even care what else happens outside them, but it will always be critically important the order that they are executed.</p><p>It’s like a mixture of order of operations and a baton relay race. That place where the baton is passed is the outlet of a function and the inlet of another function. Things must flow in the correct order to work correctly. Keep this in mind when you are working with asynchronous functions.</p><p>A clever reader might think of premature optimizations when they transform 1+1 into 2. Is that actually important? On one hand, it’s harder to package 1+1 into 2. On the other hand, it’s harder to unpack 2 into 1+1. what if you need to access 1 but it isn’t available at a particular moment in time? Think about this example for a couple minutes and imagine things being unfortunately tucked away too far, or too much crap flying around that could be trimmed down. It’s easy with 1+1, but what if instead it was 2+1+2 and a moment in time came when you needed to know how many numbers were used to make 5.</p><blockquote>Keep this in mind: the penalty of the wrong abstraction is worse than the penalty of no abstraction.</blockquote><p>The above quote that I observed once at some moment in time before now is telling us that it’s easier to untangle one function than it is to untangle 45 functions that do pieces of what the original function did. It’s the same but different. 1+1 leads to 2, or 2 leads to 1+1. Your task is to figure out the most concise code that conveys the perfect amount of meaning to make it look like poetry and mathematics had a baby in some data flow with respect to time. The poetry is in the labels, and the math is in the movement with respect to time and the relationships between labels.</p><p>Here is an aggressive example, and yes it’s horrifically labeled, but it shows some unidirectional movement from A to D:</p><pre>const d = a =&gt; (a + b + c);</pre><p>I want to just write that again another way so you can more clearly see the synchronous, deterministic flow with respect to time:</p><pre>function d(a) {<br>    const startPlusCrap = a;</pre><pre>    startPlusCrap += b;</pre><pre>    startPlusCrap += c;</pre><pre>    return startPlusCrap;<br>}</pre><p>You can see how the starting input is dragged through there towards the startPlusCrap output hole. Hole is kind of a horrible name. It looks more like the end of a tunnel doesn’t it? It’s like a tunnel that goes into a hole of unknown, and that’s fine. Notice how my super-concise, syntax sugar version above uses ( and ). I did that intentionally because it’s similar to using brackets in math. They are part of <strong>B</strong>EDMAS (aka <strong>P</strong>EMDAS). The function is implicit-returning an expression, and those variables must appear a certain way for the = to work. We don’t want any confusion.</p><p>Back to naming things, naming things is like a creative science where you have to label things so another human with no idea WTF is going on can quickly see what’s going on. There’s maybe some lesson here about context at a moment in time when you observed some code running in its natural habitat. Interestingly, less is not more when it comes to labeling things, but a certain type of beauty emerges when you find maximally efficient naming patterns.</p><blockquote>In my opinion, an Array named filteredData is generally not as good as one named filteredCountries or countriesFilteredByDate because it can make a huge difference depending where and how you see it being used inside other things. While you’re scanning code, you don’t want to be wondering things like “wtf is filtered data?”. filteredData reads more like a more verbose version of x. It’s not an exact science. Pay close attention when you have to start opening other files to see what something is. Well-chosen names can help protect against that confirmation step.</blockquote><p>A series of functions could be thought of as a component in some kind of hierarchy. Imagine the top of a pyramid is the root component. If you have multiple root components networked, you have microservices. A series of functions is conducive to composition. Imagine it like counting, 1,2,3,4,5,6,7,8,9,10. You don’t magically go back to 1 unless you add the word and on the end, or in JavaScript add the word return. The flow of numbers is one way through the chain. Note this imagery.</p><h3>DATA FLOW</h3><blockquote>Functional Reactive Programming is all about thinking in data flows over time.</blockquote><p>In Functional Reactive Programming, you are some data and you can go anywhere one hop at a time — from node to node — from a start to a finish. You can chain these hops, but it’s a special way of thinking. Something is generally always listening and then acting or doing and then triggering. Stuff can listen to <strong>events</strong> and trigger <strong>actions</strong>. This whole time, the <strong>state</strong> integrity must be maintained. Functional Reactive Programming emerges as a way to apply patterns to this kind of stuff. Changes are very formal so no one gets screwed up. Remember — order of operations.</p><p>Functional Reactive Programming is about pushing towards something or pulling something to you, one step at a time. Rather than one step, you could say one section at a time. Let me describe that slightly different. When you start something, you should finish it. When we draw that on paper, it looks like a fancy graph of <strong>actions</strong> and <strong>events</strong> over <strong>time</strong>. State isn’t mentioned there, but you can see it by looking at function inlets and outlets.</p><p>The point is, we are adopting a mathematical approach. Various patterns emerge when we study things with respect to time.</p><p>Checkout this visual sampler pack of you starting and finishing something and experiencing things along the way:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/879/1*skM9jz2dY7wc06yta3ttOw.gif" /><figcaption>Fig 1.4 — Functional Reactive Programming (FRP)</figcaption></figure><p>I think this article will work better if we don’t load you up with JavaScript code examples. Let’s try instead to focus on how to think and why we look at certain types of code.</p><h4>Directed Acyclic Graph (DAG)</h4><p>In the React world, you will eventually encounter this thing called a Directed Acyclic Graph. You barely know me, but I love studying nodes and relationships between them. I eat pieces of nodes for breakfast. My digestive system is a unidirectional flow over time.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/318/1*hd52yl1nfU2XQDVIdEddqg.png" /><figcaption>Fig 1.5 — Directed Acyclic Graph (DAG)</figcaption></figure><p>When mathematically analyzing a React app, it should look like that DAG. Imagine the first node is <strong>where and when</strong> some data comes into the picture — maybe from your API. Imagine the last node is <strong>where and when</strong> it gets rendered on your screen. JSX is the language we speak <strong>at</strong> the last node. Get used to it.</p><p>The top of the DAG looks like this usually:</p><pre>render(<br>  &lt;App /&gt;,<br>  document.getElementById(&#39;root&#39;),<br>)</pre><blockquote><strong>Remember:</strong> we must first discuss a bunch of crap related to weather and climate before we start talking about the Aerodynamics of Wind Movement. Wind is the movement of air from an area of higher pressure to lower pressure. There is a pressure gradient force. The sharper the drop in pressure, the faster the wind measured. Data flows exactly like this — only way different. We have to wander into a bit of complexity before we can simplify it.</blockquote><h4>Flow</h4><p>Data can flow both ways. It may first flow unidirectionally from server to client, and then it may flow back unidirectionally. It’s like a one way street beside a one way street. Some call it a road. Chaos occurs immediately if this flow rule is broken. You wouldn’t send data to the server through your GraphQL get query, or would you? No, you wouldn’t. Data flow is best served unidirectionally. It’s simpler to reason about.</p><p>You might be saying, “<strong>hey wait what about two-way binding?</strong>” It’s still happening unidirectionally. The button press always leads to the button press event which always leads to the state update action which always leads to the UI reflecting the result of that update. State, events, and actions — there they are emerging again. They always do.</p><p>Data-centric apps are best served with this type of logic because data flows inside the network that contains it. Data is like a type of energy. It can cause a chemical reaction that cannot be undone. If someone posted a photo on Facebook of you wearing a cheetah-print pajamas while you were crying, you would understand how data can create a chemical reaction. Once you see it, you can’t unsee it. Data also moves like a fluid. It can create a huge mess if certain kinds of this liquid leak out.</p><blockquote>The internet is a series of tubes, and so is your app.</blockquote><h3>PART ONE — THE IMPORTANT THEORIES</h3><h4>Patterns and Anti-patterns</h4><p>Study of JavaScript and React brings mentions of anti-patterns into the mix. When a normal human sees things, they have normal knee-jerk reactions. An anti-pattern is a response to something that is a normal but <strong>sub-optimal</strong> response. Everything comes back to patterns, flow patterns.</p><p>Try not to make fun of someone that isn’t familiar with your patterns. They may be reasoning about the situation from a different <em>angle</em>, and this will change the way things appear. Just as I used the word this a second ago, the word this can change depending how you analyze some data. Let someone know your pattern. Draw it for them. See if they still disagree. But, talk about it like Bill Nye to Bob Ross composed with Mr. Rogers.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/1*dKbHsZIae2l7ZAByf60Rhg.jpeg" /><figcaption>Fig 2.0 — Bob Nyegers: he paints nice logic in your neighbourhood.</figcaption></figure><p>You may or may not notice immediate benefit from these flow patterns, but you will benefit from knowing they exist. After all, JavaScript was once a savage and choatic environment, perhaps like Mars is or Earth once was. Data was gained, keyboards were smashed like WWE Wrestling, but the JavaScript beast was tamed — at least more than it was anyway. LOL. That is a cop-out statement.</p><blockquote>In JavaScript, things flow the best over time immutably and unidirectionally. Why? Because of live references and dynamic typing.</blockquote><ul><li><strong>Objects contain data.</strong></li><li><strong>Functions instigate movement of data.</strong></li></ul><p>Functions can create action, like pushing a ball with <em>just</em> enough force to roll down the stairs and completely destroy my sister’s Mousetrap game that was setup.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2ajMmZYDFJI9Wkkhie6l4A.jpeg" /><figcaption>Fig 2.1 — Mousetrap Board Game</figcaption></figure><ul><li>Notice how pushing a ball down the stairs is a one-way action as <strong>part of</strong> an event.</li><li>Notice how Mousetrap is a <strong>series</strong> of contraptions and a one-way system. If you ignore every point in time individually at first, you can study the system as if it were in continuous motion (ie: Calculus and deterministic transformation formulas).</li><li>Notice how each contraption always produces the same result unless you get violent or introduce an unexpected flow over time, like turbulence. Try putting a large fan beside the game and see what happens when you mutate the air pressure values around each contraption.</li></ul><blockquote><strong>Note:</strong> forget about <em>deterministic transformations</em> for now. Your brain may catch on fire. I only mention it for the guy with the beard and his coffee. Let’s also note the gender-specific reference here and always be mindful to include females and non-binary individuals — they can also code great if they choose to.</blockquote><blockquote>Deterministic means, “if you put in the same input, you get the same output 100% of the time.”</blockquote><p>If I <em>always</em> roll a ball down the stairs, and it <em>always</em> destroys my sister’s Mousetrap game, my mom may not appreciate that pattern, but at least I can tell her it is deterministic.</p><p>I refuse to go anywhere else before I supply you with definitions for live references, immutability, and garbage collection. These next things make the most sense if you ask yourself how they are related to <strong>unidirectional travel over time</strong>.</p><h4>Live References</h4><p>In JavaScript, Functions are first-class citizens. What does that even mean? It means that in JavaScript, everything is an Object. Functions are Objects too, so that’s at least confusing, but Functions are a first-class citizen because all JavaScript does is start executing the first line of code and then stops when it’s done. Remember the order of operations? JavaScript just executes functions as fast as it can one at a time.</p><blockquote><strong>Slow down</strong>: It’s understandable if that doesn’t fully make sense. To understand more, you will need to research the JavaScript event loop which has a call stack, function queue, and the heap. The call stack is single threaded, so you can only process one function at a time, but the good news is you can load up an infinite number of functions in the queue and they will complete as fast as they can according to laws of Mathematics and order of operations.</blockquote><p>The JavaScript engine is basically executing functions by passing them through the call stack one at a time (this is where the word synchronous comes from), but JavaScript also has a function queue, which is where functions that aren’t quite ready yet will be placed. We call this area the event loop, and you should research it — and not just once. You should read about the event loop once per month for the next two years. I’m serious. It’s a good idea to try to fundamentally master the event loop idea. Your ability to solve extremely crazy asynchronous bugs depends on it.</p><p>Think of it this way. When people buy stuff, they use money — units of currency. In JavaScript, the unit of currency is Functions. They may contain things, but you can imagine functions floating around. Everything happens inside functions. They are containers for work. They have a discrete start and a discrete finish (hint: unidirectional).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/1*Drz5Lwh2WtLcZdrxXg7JTQ.gif" /><figcaption>Fig 2.2 — Pass-by-reference vs. pass-by-value</figcaption></figure><p>When people say live references, they are talking about pass-by-reference. Objects and Functions maintain a live reference to a single source of truth. It’s like your home address, except the data lives inside the computer’s memory (or another location if you want to get crazy). The point is it’s somewhere exact, and it’s only that place your app refers to.</p><p>Here is an example of creating an Object in JavaScript:</p><pre>const sandwich = {<br>    flavour: { confirmed: &#39;pretty good&#39; },<br>    isTasty: getFlavour(sandwich.flavour),<br>}</pre><p>You can see here the Sandwich Object has properties such as flavour, but it can also <strong>look at itself</strong> in real-time if you give it a function to do so. Well that’s kind of weird, but we like it. In that example above, the Object maintains a reference to getFlavour(). This is fundamental to immutable JavaScript. It is a common task to break references and throw them in the garbage. Part of your job as a JavaScript programmer is to manage these references effectively.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/560/1*KDeikETx8W1cIwU65dThjQ.gif" /><figcaption>Fig 2.3 — Look at this as if it were a single object that doubles as a function too</figcaption></figure><blockquote>Where this becomes dangerous is real-time pass-by-reference analysis.</blockquote><p>Remember how the start of a function and the end of the function is the most important time and place. If the end of a function is relying on a live reference, the reference must be correct — or you’re screwed. It’s perfectly valid to take special precautions in your own code to ensure this data is always correct. In my books, you are safe to get excited about trying to protect your data (ie: state: the state of the data at a moment in time when observed).</p><p>What do you think would happen if you started producing hella sandwiches with your function and someone changed what was inside getFlavour()? We might start to see some pattern violations. You must be able to rely on the <strong>same output</strong> every time you give the <strong>same input</strong>. This is our first sampler pack for live references.</p><blockquote><strong>Advanced Note:</strong> This is also rule number 1337 for function composition. You can’t create a series of events and “set your clock to it” if you change the third step to modify the clock’s time by a random amount 50% of the time. That sounds weird and it produces unreliable results. It’s not mathematical, and you don’t want it in your app… unless you’re working on <em>TrollCalculator.exe</em>.</blockquote><p>If someone changes sandwich.flavour right before you eat it, you may experience something undesirable if you measured sandwich.isTasty immediately after. Case in point. The cure for this potentially-horrendous flavour <strong>at the time of measurement</strong> is called immutability.</p><h4>Immutability</h4><p>Immutability is great because you can relax once you set data in place. You don’t have to worry about data or sandwich flavours getting unexpectedly mangled if someone else happens to observe that single source of truth around the same time.</p><p>In JavaScript <strong>with</strong> immutability, an Object is like a piece of paper with some writing on it, and you can fold it up and throw it like an airplane. If it was built with correct patterns, it could travel as far as possible as efficiently as possible. That’s what survival of the fittest looks like in programming. It’s what maximum <em>efficiency </em>composed with maximum <em>effectiveness </em>looks like.</p><p>If the airplane mutates along its journey, that’s not for you to decide when you throw it. Your job then is to throw it with the correct parameters. This is so important that you will see hand waving and emphasis in real life.</p><p>Your job as a programmer around this time is to imagine, ‘what would happen if everything about my app changed before or after this moment?’ It’s hard to predict the future and hard to control the past, so you should try your best to make the <strong>past</strong> and <strong>future</strong> not important for <strong>current</strong>. This means you should try to supply what will be needed now, and not worry about what will be needed later.</p><blockquote>Immutability can free you from trying to predict the future and recount the past. Who cares where we came from or how we got here. We care where we are going next and how we are going to get there.</blockquote><p>If you want some mental imagery, imagine traveling lean vs. hoarding. Remember, we are traveling unidirectionally. We have to supply everything without being wasteful. <strong>Data waste translates into extra CPU, memory, and bandwidth usage. </strong>It can also create leaky abstractions by leaking out too much information. Be careful out there.</p><p>This whole supplying too much or too little thing is fairly key to function composition and creation of chains of functions. If you make a long chain that goes deep under ground, it’s not efficient to go back and grab something you forgot. You don’t have to predict the future as much as it sounds like though. There is something very special we can do. We can pass objects through the function chain.</p><p>Check out this next example. Let’s pretend we are going to create a function that paints a news article onto your screen using JSX. If you’ve never seen this pattern, pay close attention:</p><pre>const config = {<br>  title: &#39;Sandwiches can produce good flavour&#39;,<br>  author: &#39;Alice Bobson&#39;,<br>  timestamp: 128364096092,<br>}</pre><pre>const renderArticle (config) =&gt; {<br>  return (<br>    &lt;div&gt;<br>      &lt;h1&gt;{config.title}&lt;/h1&gt;<br>      &lt;h3&gt;{config.author}&lt;/h3&gt;<br>      &lt;span&gt;Created: {Date(config.timestamp)}&lt;/span&gt;<br>    &lt;/div&gt;<br>  )<br>}</pre><pre>renderArticle(config)</pre><p>The thing I want you to pay attention to is the fact config is one Object, and it is getting passed into the renderArticle() Function. The function expects to be supplied with what it needs. We could create a unit test to ensure config always goes in. We could add logic to the function to make it explode if title, author, or timestamp are not Strings or are missing. Notice how the code example looks fairly neat as well. It’s quick and easy to understand.</p><p>Tomorrow, we might remove the timestamp because someone complained it was too ugly. That’s fine, just remove two lines of code. Do you notice anything else? Yes, we forgot to put content in there. That is a pretty terrible article. Let’s fix it:</p><pre>const config = {<br>  title: &#39;Sandwiches can produce good flavour&#39;,<br>  author: &#39;Alice Bobson&#39;,<br>  timestamp: 128364096092,<br>  content: &#39;Today, we added one key to an object, and we found that<br>            our code was easy to test, extend, and maintain.&#39;,<br>}</pre><pre>const renderArticle (config) =&gt; {<br>  return (<br>    &lt;div&gt;<br>      &lt;h1&gt;{config.title}&lt;/h1&gt;<br>      &lt;h3&gt;{config.author}&lt;/h3&gt;<br>      &lt;span&gt;Created: {Date(config.timestamp)}&lt;/span&gt;<br>      &lt;div&gt;{config.content}&lt;/div&gt;<br>    &lt;/div&gt;<br>  )<br>}</pre><pre>renderArticle(config)</pre><p>What this means is the code is mostly hands-off once it’s working. You won’t have to restructure it very much if you add or remove anything. It’s a demonstration of both object composition and function composition. It’s a demonstration of why we usually like declarative code.</p><p><strong>Let’s reflect on these key factoids:</strong></p><ul><li>Our function expected to be supplied everything it needed</li><li>We supplied our function with everything it needed</li><li>We stored everything in a config Object</li><li>The function performed an action, deterministically</li><li>Our pattern is very robust</li></ul><p>In our example above, the logic is unidirectional. See how the data is flowing one-way over time? Data flows in at the top and then flows out. It will <strong>render the same</strong> article every time you <strong>pass the same</strong> values for title, author, timestamp, and content. You can trust the heck out of that render function if you can trust your config values are correct when the function starts.</p><p>Notice that even the DOM markup inside that function has an order to it: first, you drop the &lt;div&gt; onto the page, then you drop the &lt;h1&gt; heading and put the title in it, then you drop the &lt;h3&gt; heading and put the author in it. It’s kind of like a 3D printer, printing the UI layer by layer.</p><p>Back to immutability — storing a piece of paper with a word on it at the corner of your desk can be done immutably if we use a pen instead of a pencil. If we want a different word on the paper, we can just put a different piece of paper there with the new word. It’s no big deal. In JavaScript, it costs like 2 cents to perform this switch:</p><ol><li>copy the Object to a new one,</li><li>stop referring to the old Object,</li><li>start using the new Object <strong>from that moment on</strong>.</li></ol><p>Here’s a real example:</p><pre>const user = {<br>  firstName: &#39;Alice&#39;,<br>  lastName: &#39;Bobson&#39;,<br>}</pre><pre>// We just learned Alice&#39;s age. We need to add it.</pre><pre>const userWithAge = {<br>  ...user,<br>  age: 1337,<br>}</pre><pre>return userWithAge</pre><blockquote><strong>Note</strong>: if you need to research the <em>spread operator</em>, then go ahead and load up another browser tab for that. That’s the <em>...</em> symbol above.</blockquote><p>We could have done user.age = 1337, but that is <strong>not</strong> thinking immutably. Since we will never mutate user after it is created, we know it will have the correct data in it when we go to copy it. This whole immutability thing becomes super important in asynchronous code.</p><p>We might have multiple areas of an application reading user at the same time. Sometimes 0.15 milliseconds is enough to ruin your life. It’s not enough to feel comfortable just because we know we can do user.age = 1337 today. What happens if someone modifies another part of your application tomorrow and isn’t aware of that mutation? Immutability is a protective force and a protective layer.</p><p>Now you are understanding. I know you hear me.</p><p>Immutable, unidirectional data flows can lead to simpler apps. If data always travels one way, you can look for the exact moment in time something went wrong, and look upstream leading up to that moment in time. You will also want to look at what other functions are trying to do at that moment in time. This is true especially when it comes to mutating data or this.setState() in React. I wrote another article about setState that you may enjoy reading later:</p><p><a href="https://medium.com/@agm1984/reacts-setstate-is-a-special-function-and-it-helps-with-asynchronous-concurrency-669eddbe3dd1">React’s setState is a special function, and it helps with asynchronous concurrency</a></p><p>Unidirectional data flow is easier to reason about because it’s simpler. It’s simpler because you are generally caring the most about what data or state is right now, not before or after. There is a distinction however between simpler to reason about code and <strong>simpler code</strong>:</p><pre>const fn = x =&gt; ({ x })</pre><blockquote>Remember, the shortest, most concise possible code isn’t always the simplest to understand.</blockquote><p>Just because something is more concise or more simple <strong>looking</strong> does not mean it is simpler to reason about or quicker to understand. Have you ever seen code that someone told you is the fastest possible way? Does it look like cryptic garbage that makes your brain hurt immediately? It’s like sending a zip file into someone’s brain and forcing them to unpack it before they can understand.</p><p>In the case of Redux, some people find it’s too much boilerplate. This means they don’t like the verbose way it makes them accomplish a task. In Redux, state, events, and actions flow <strong>only-forward</strong> in time (ie: they move only in the positive direction). When you are comparing things over time, you can rely on first-on first-out (FIFO) logic.</p><p>Redux embodies unidirectional flow and immutability. Try not to hate Redux until you understand its patterns. What Redux gives the world is a formal state-change management process that is easy to reason about, at least in theory. We can always make a complex program that makes simple ideas inevitably complex. Anyway, let’s move on.</p><p>Think of immutability like the Ronco Food Dehydrator:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/925/1*9BJv2BAptPbUoeJ9VUkjJQ.png" /><figcaption>Fig 2.4 — Ronco Food Dehydrator</figcaption></figure><p>Immutability works best when you let data flow unidirectionally. This way, <strong>asynchronous code can appear synchronous</strong> because everything is “over time” (ie: from the start of the function to the end of the function). This is the pinnacle of declarative code, and it makes sense because time moves one way. It’s easier for your brain to handle.</p><p>Think of an <strong>action</strong> or an <strong>event</strong> as a function that gets triggered at a particular moment in time. When is always significant. If a bug happened, something happened at the wrong time and mangled your perfect deterministic flow pattern. Similarly, something may have not happened at all at the perfect time.</p><p>This leads me to my next point. After the time passes when some data or functions are no longer needed, they become garbage. Who better to come and clean up those live references than the garbage collector. What does this magic “GC” do?</p><h4>Garbage Collection</h4><p>To understand this deeply, we can re-visit our immutable pen and paper example. If you replaced the old paper with the new paper but you never got rid of the old paper, your home would quickly look like this photo:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*6qzBQ3k6Tt8Jz9b4iN-Brw.jpeg" /><figcaption>Fig 2.5 — Depiction of the JavaScript heap without Garbage Collection</figcaption></figure><p>To combat this problem in real life, a garbage truck periodically drives by every two weeks. The driver fills his nostrils with magical garbage scent as he takes that landfill nectar away from your home.</p><p>In JavaScript, it is slightly different. JavaScript garbage collection happens when nothing in the current execution context refers to an Object any more. Everything is more complex when you zoom in, so let’s keep it that simple.</p><blockquote>In JavaScript, the execution context is usually a function being executed.</blockquote><pre>const garbage = () =&gt; {<br>  // when you stop referring to me, I will be gone<br>  return &#39;cool&#39;<br>}</pre><pre>const generateGarbage = () =&gt; {<br>  const createReference = garbage()</pre><pre>  if (createReference === &#39;cool&#39;) {<br>    // perform some work<br>  }</pre><pre>  // as soon as we arrive here during code execution,<br>  // JavaScript unloads `garbage` from memory<br>  return &#39;that is very cool&#39;<br>}</pre><p>In the example above, JavaScript puts garbage in the memory as soon as it encounters it. That occurs at the first line inside generateGarbage(). JavaScript must hang onto that reference in memory because it knows you will refer to it again soon and because loading things into memory costs CPU time. JavaScript is super fast because of this, but you can get into trouble.</p><blockquote><strong>General Rule Note:</strong> As soon as you know you no longer need a reference, ask yourself, is this going to get garbage collected now? Your goal is to notice when the answer is no. This is how you avoid memory leaks. It is a key JavaScript skill.</blockquote><p>Garbage collection is like a robot helper following your functions around and auto-dumping your no-longer-needed Objects and Functions into the trash shoot of an apartment building.</p><p>I don’t want you to freak out because this stuff isn’t exactly easy. If you aren’t very familiar with it, it’s normal. Spend a bit of time studying them. Here’s a good article to give you some things to think about: <a href="https://auth0.com/blog/four-types-of-leaks-in-your-javascript-code-and-how-to-get-rid-of-them/">https://auth0.com/blog/four-types-of-leaks-in-your-javascript-code-and-how-to-get-rid-of-them/</a></p><blockquote><strong>Garbage Note:</strong> Garbage Collection is cheap. It’s so cheap, we don’t really care about its cost until our JavaScript problems become more serious than “what is functional programming?”. We don’t care too much about premature optimization. StackOverflow.com will help as soon as you describe a Garbage Collection-related problem.</blockquote><p>Understanding this stuff intuitively may not happen on the first pass. Based on my observations, some people do not love JavaScript, React, or JSX. If they are not familiar enough with JSX, we cannot be mad at them for being skeptical towards the unknown, but we can help them understand more. New insights can flow towards you from new data. Send haters this article, and they will at least leave you alone for a while since it takes a while to read, LOL.</p><p>None of my articles will make sense if we aren’t approaching software as a set of smaller problems and solutions that are composed together to create one solution. Kind of like a <strong>Singleton</strong>. If you look at it, it displays the <strong>correct </strong>data at that moment in time <strong>when you look</strong>ed. Sounds like data is important right? Data flows through a series of tubes, channels, or streams. Tune in to channel 5 to see how many users are logged in currently.</p><blockquote>I’ve hidden a secret puzzle in the bolded words above.</blockquote><p>Now, we are about to push into some more advanced territory. Imagine it this way, we are coming into this new material here, and I’ve supplied you with everything I think you need to properly reason about this.</p><p>We studied unidirectional flow, live references, immutability, and garbage collection. We are now going to start composing those more basic ideas into something that will blow your socks off.</p><h3>Function Composition</h3><p>This is the meat and potatoes of functional programming, and it’s a secret layer behind reactive programming. After all, you can’t use <strong>map</strong>, <strong>reduce</strong>, and <strong>filter</strong> if you can’t chain them onto the end of a collection of data (ie: an Array) that’s flowing somewhere.</p><p>You can compose not only functions but also entire data flows together as long as everything together flows one way and is deterministic. There is a thing called <strong>determinism</strong>. With respect to functions, a deterministic function produces the same predictable output when you put in the same input. These are <strong>pure functions</strong> and they are worth studying at great length in your spare time.</p><blockquote>A deterministic function produces the same output when it is given the same input.</blockquote><p>In programming, there is a thing called referential transparency. It means, if you swap out a function for its <strong>computed counterpart</strong>, the application would still function identically. You can’t have referential transparency without a deterministic function.</p><p>Here’s an example because referential transparency makes everything easier to understand:</p><pre>const ok = 33</pre><pre>const getNumber = num =&gt; num // returns 33 if you input 33</pre><pre>const correctAnswer = 1 + getNumber(ok) + 7</pre><pre>console.log(correctAnswer) // returns 41</pre><p>In the example above, if you swapped out getNumber(ok) with 33, correctAnswer would still return 41. That is referential transparency, and it will be an incredible boon to your ability to create bug-free, easy to change code.</p><p>Take a look and imagine some data flowing through here:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0FyWDstQ7i0FDXIyU3tBQA.png" /><figcaption>Fig 3.0 — Function composition</figcaption></figure><p>Check out that radical cube there. What do you think would happen if g() randomly output something unexpected 50% of the time? That would mean f() would receive something unexpected 50% of the time, and everyone would have a bad time… 50% of the time all the time. Also, good luck putting both of those functions into another function that is feeding the result of g() into f().</p><blockquote><strong>Brain Helper Note:</strong> g feeds into f and both are deterministic.</blockquote><p>If this was in JavaScript, it would look like this:</p><pre>f(g())</pre><p>If you ever studied Calculus, you may be thinking to your self, holy expletive, this looks and sounds familiar. If you did not study Calculus, then imagine people drawing triangles inside semi-circles and realizing they can estimate things infinitely close to exactly correct — things such as total distance, surface area, speed, and energy use over time or at exact moments in time, <strong>if they were supplied enough information</strong>. Does that remind you of composing some functions together with supplied data? What if we switched the word function for equation?</p><blockquote>What if we used <strong>equational reasoning</strong> and said that function = equation?</blockquote><p>If a function is an equation, then we could always try to compute something and update state or return something.</p><p>You could think of state updating like a:</p><ul><li>push</li><li>put</li><li>set</li><li>do</li><li>write</li></ul><p>You could think of returning something like:</p><ul><li>pull</li><li>get</li><li>bring</li><li>collect</li><li>read</li></ul><p>Return is a pivot point. If you look at an answer to ‘what is returned?’, you see where the function landed and what the state will be.</p><p>Let’s see a JavaScript example. Let’s imagine we are data, and we are traveling to the other side of this goToLocation function:</p><pre>const locationX = &#39;http://www.com/profile.html&#39;</pre><pre>const config = {<br>    name: getProfile(&#39;Reader McGee&#39;).name,<br>    start: &#39;1337.html&#39;,<br>    end: () =&gt; next(locationX),<br>    error: () =&gt; next(&#39;404.html&#39;),<br>}</pre><pre>// destructuring not used in order to show correlations<br>const goToLocation = (config) =&gt; {<br>    if (config.start !== &#39;1337.html&#39;) {<br>      return config.error()<br>    }</pre><pre>    return config.end()<br>}</pre><pre>goToLocation(config)</pre><p>If you come across this code above, you could ask yourself:</p><ol><li>Where is it going?</li><li>What is being returned?</li></ol><p>We could burst in with a bit of equational reasoning again and say:</p><blockquote>Where it is going <strong>=</strong> What is returned</blockquote><p>The function takes one hop and computes where it is going. As you can see, the function expects to be supplied: config.start, config.error, and config.end. The important thing here is that the data changes but the structure around it never changes. This is why it’s like an equation, except it’s more powerful because you can add logic like:</p><pre>if (today === &#39;monday&#39;) use(&#39;multiplication&#39;)<br>if (today === &#39;friday&#39;) use(&#39;division&#39;)</pre><p>All that matters to the function is it’s getting supplied the correct data and it’s going somewhere and/or returning something. If a function doesn’t reach outside itself for any reason, then there are no side effects, and it is deterministic — and unidirectional as well.</p><p>You could make a unit test that checks that. Such a unit test could check that the correct output was returned for a given input, then we would know everything was working as intended.</p><p>Upon my later inspection, the goToLocation example may be a bit difficult to understand the first time you encounter it. I will help us by pointing out a couple facts:</p><ol><li>The function is being supplied what it needs</li><li>The data being supplied is dynamic, but the operations in the function are static</li><li>The data types are static. We are relying on this fact.</li><li>The function returns something</li></ol><p>I think a good way to look at chaining functions together is to consider that you are wiring up a scaffolding or a series of channels, and then you are energizing them with data after. A chain of functions is like a structure. The intent is to wire up everything so that you can freely change little pieces here and there without completely refactoring everything.</p><p>This results in time-savings later because you never know what might have to be changed. A good function is one that can easily handle unknown types of changes later.</p><p>When functions always return something, functions can become answers to questions. For example,</p><pre>const users = getNumberOfUsers()</pre><p>When functions always return something, they always finish with a final step similar to handing in your homework at school. Your app can check the final outcome and make sure everything is normal.</p><p>The important thing to keep in mind is that data is flowing unidirectional over time. The data is flowing from start to finish (and from parent to child), perhaps from your API towards being rendered on your screen. Look at <strong>Exhibit A</strong> again. Maybe g() is getTheBlueIcons() and f() is setTheBlueIcons(). Now, look at <strong>Exhibit B</strong> again. Maybe f•g() is renderIcons(&#39;blue&#39;). As long as you got blue under control, you can sprinkle a bit of win sauce on your app.</p><p>What we are actually doing here is thinking declaratively. We are declaring what the start condition and the finish condition look like. If something goes wrong and you know your start condition is correct, then you know where the problem must be. We are thinking “with respect to time”.</p><p>Do you know what Exhibit B really is? It’s a pattern. It’s function composition. Some awesome people noticed this a long time ago, such as Isaac Newton and Gottfried Wilhelm Leibniz.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RhEpyMyTHHs0RvmBSQwtAg.png" /><figcaption>Fig 3.1 — Gottfried Wilhelm Leibniz</figcaption></figure><blockquote><strong>Quick Research:</strong> <a href="https://en.wikipedia.org/wiki/Gottfried_Wilhelm_Leibniz">https://en.wikipedia.org/wiki/Gottfried_Wilhelm_Leibniz</a></blockquote><blockquote>My brain, Gottfried! WTF were you doing in the year 1700 AD?? Is this real life??</blockquote><p>It used to take me two pages to answer one question in Calculus. Keep that in mind when you realize these guys were from 1700 AD.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/451/1*_KutSqxuCw0G1xKqQk_mvA.gif" /><figcaption>Fig 3.2 — Luckily, I don’t need to do this in JavaScript</figcaption></figure><p>The order that things occur inside your application is very similar to BEDMAS or PEMDAS (order of operations) when doing Math. In the above image, the important thing is that everything happens in an exact order over time. Because the order is predictable and the functions are deterministic, the finish value is predictable if the start value is predictable.</p><p>The difference is you are doing Math with units of logic instead of numbers. Remember, a function is just a place to do work. The name of the function acts as a label. If you follow some rules, you can unlock mathematical precision.</p><p>More specifically, you don’t have to load up your short term memory with 900 small details of imperative code that “gets users from a database” if you can boil it down to a function called getUsers. Now every time you see your code, you see one word: getUsers. It’s a solved problem; no one cares what’s happening inside that function as long as it works correctly when it is called. This makes your code look really simple, so it stays relatively pretty easy to understand what’s happening. You can see the important details, concisely.</p><p>If the function was instead called getUsersAndAddTimestamps, then again, all the important information is captured in one word. No matter where you see it, you know what’s happening inside that function. You don’t have to look inside it.</p><h3>Conclusion</h3><p>Alright, now we are familiar with composing deterministic functions while immutably flowing one way.</p><p>Think of your functions like formulas or equations. If you put some stuff in, you will get what? Do some bonus research now into shared mutable state and side effects. Shared mutable state is the more complex answer to, ‘why do we care about immutability?’ Side effects are the more complex answer to, ‘why are deterministic functions so good?’</p><p>I use the term deterministic instead of pure because it is more academic, so you will find scientific information very quickly when you use Google to ram your head into the keyboard.</p><p>I’m thinking about a more complex version of this article and how to execute these ideals in JavaScript. Until then, you could follow me on Twitter or Medium or a number of other places if you are interested. According to other people, I tend to spray out gems.</p><p>I typically randomly burst out information that is valuable towards JavaScript, React, React Native, Vue, node.js, QA, UX, and even Economics and Marketing. I love revenue-generating assets and compound interest. My screen name is usually agm1984. I am in love with the equation ui = fn(state). As state changes, the UI reflects exactly those changes. The deltas are proportionate.</p><p><a href="https://www.twitter.com/agm1984"></a></p><p>If you simply cannot wait to learn more, I recommend reading Eric Elliott’s article about function and object composition. Now that you’ve read this article, you may find Eric’s words about object and function composition very timely.</p><p><a href="https://medium.com/javascript-scene/composing-software-an-introduction-27b72500d6ea">Composing Software: An Introduction</a></p><p>In closing, like I said back at the beginning of this article, immutability is how you can sidestep many problems, and it’s the basis for unlocking the power of Math and the continuous motion of data flow, and if your state gets screwed up at any moment in time, chaos will emerge, so focus on guaranteeing state integrity. Your state changes should be very formal.</p><p>Functions can always operate within bounds, so there can be a lower bound and an upper bound. I’m catering to a bit of logic related to digital vs. analog values. If the value can be within -100% to +100%, anything outside that is out of bounds and your function should get mad at that moment in time. 0 is in the middle, so the distance between -100% to 0 and 0 to 100% is identical. Any function can always check its values before it completes.</p><p>Keep your types static. If it’s a String, it should always be a String, even if it’s empty. Use default values and default state. Focus on accumulating final products. Every function can start with some input to use as part of it’s default state, and then every function can also end with some output that was accumulated starting from the default state.</p><p>You don’t have to understand everything I described in this article, but you can latch onto details that have meaning for you today. Practice them.</p><p>I will leave you with this final imagery to help <strong>our</strong> imposter syndrome. You probably always see everyone’s code seems to look a bit different and you don’t know what “the best” really is. This is true for the same reason that if you told 5 artists to make a sculpture of a human head, all 5 of them will look different but all 5 of them will look like a nicely-done human head.</p><p>Your “created code” is no different. It will look different because you are a unique individual with unique strengths and weaknesses, but if you are appealing to the laws of mathematics and physics that the Universe revolves around, then your code probably looks great because <strong>form follows function</strong>. Good code looks like good code. Certain things are generally good, and certain things are generally bad.</p><p>The simplest solution tends to be the correct solution: look up the definition to the Occam&#39;s Razor. Go make a bunch of reuseable utility functions and compose them together at moments in time when you can use them. Remember to supply your functions with everything they need so they don’t need to reach outside themselves to operate correctly.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=10d75b509e9e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to rig a character model for THREE.js in Blender]]></title>
            <link>https://agm1984.medium.com/how-to-rig-a-character-model-for-three-js-in-blender-846e258a9d9d?source=rss-62ac59fdc132------2</link>
            <guid isPermaLink="false">https://medium.com/p/846e258a9d9d</guid>
            <category><![CDATA[threejs]]></category>
            <category><![CDATA[blender]]></category>
            <category><![CDATA[rigging]]></category>
            <category><![CDATA[animation-fundamentals]]></category>
            <dc:creator><![CDATA[Adam Mackintosh]]></dc:creator>
            <pubDate>Sun, 22 Apr 2018 00:13:14 GMT</pubDate>
            <atom:updated>2018-04-22T00:15:34.878Z</atom:updated>
            <content:encoded><![CDATA[<p>I started making notes for myself about Blender hotkeys, but I realized I should put those notes on an electronic medium, keyword searchable for my future self. This article should be all I need in the future to get a model rigged up in Blender.</p><p>This article is part one of what could be at least 3+ articles related to THREE.js. Let me know if the comments at the bottom if you need more data like this.</p><p>I like JSON because it is inherently free and open source and aims to be fairly universal.</p><p>This article is based on this video from Sebastian Lague and it should make for the perfect companion to this text:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FcGvalWG8HBU%3Ffeature%3Doembed&amp;url=http%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DcGvalWG8HBU&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FcGvalWG8HBU%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/f4edf4a72d4fb9297b2e8783ba3cade6/href">https://medium.com/media/f4edf4a72d4fb9297b2e8783ba3cade6/href</a></iframe><p>This article was created in approximately chronological order of steps taken. Here are the approximate steps:</p><ul><li>Open Blender file or Import Model</li><li>Place Bones</li><li>Place IK Bones</li><li>Adjust Bone settings</li><li>Place Control Bone</li><li>Customize controls</li><li>Done</li></ul><blockquote><strong>NOTE</strong>: When working in Blender, the Mode you are in is very important.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/783/1*qBcxDT5yWWue2UemJiRikw.png" /></figure><blockquote>If your hotkey isn’t working, check which mode you are in.</blockquote><p>I’d even go as far as to say that approximately 13.37 out of 10 times, being in the wrong mode will cause a problem. Many tutorials gloss over or assume which mode you are in, so you must watch closely. This gets easier as depth of Blender knowledge increases.</p><blockquote><strong>Bonus FYI</strong>: Press and hold the mouse wheel down to move the Camera.</blockquote><h3>Theory</h3><p>Today, we will be rigging a bipedal locomotive or as some call it, a human. The science behind human movement can escalate quickly. I am going to show you how to rig up a human in as few bones as possible while retaining life-like movement. You can employ these techniques on any model.</p><p>Here is a photo that is representative of what we are doing:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/539/1*gbYsdER3J4NTer0rhvMD7A.png" /></figure><p>We will be employing a bit of special magic to get the feet bending nicely and similar magic to get the arms moving realistically at the elbows.</p><h3>Preparation</h3><p>Open Character Model in Blender</p><h3>Bones</h3><blockquote>If this is your first bone, press <em>SHIFT + C</em> to center character. You will see the red/black/white cursor target snap to the center. If you are reading this now, try pressing it. It is a non-invasive event that moves the Camera to origin(0, 0, 0).</blockquote><h4>Add Bone</h4><p>Adding a bone is as simple as pressing: SHIFT + A if you are in Edit Mode.</p><p>If for example, you want to add a bone starting from the shoulder, Left Click the shoulder to put the target cursor there, then press CTRL + A.</p><h4>Enable Bone X-Ray</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/431/1*J-Ee6IYWp6xP0J83Mou4cg.png" /></figure><ul><li>In the right-side properties pane, Select Armature</li><li>Check X-Ray</li></ul><h4>Resize Bone</h4><ul><li>Right Click a Joint to select it</li><li>Drag the X, Y, Z axis arrows to mutate the dimensions</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/596/1*qi2p9e4A5uXtkgiIvjhskA.gif" /></figure><h4>Move Bones</h4><ul><li>Right Click a Bone to select it</li><li>Hold SHIFT + Right Click to select multiple bones</li><li>Press G to move the selected bones</li></ul><blockquote><strong>TIP:</strong> Use the number keys on the numpad to quickly place the Camera. Try pressing 0–9 on the numpad now. See what is happening? Press 0–9 again. Now, spam them at random like you are playing a song. Very nice.</blockquote><p>Why do I care to mention the Camera placement? Because you can move the Camera on demand and see if your bone is <strong>centered inside the model</strong>. Remember, we are dealing with 3 dimensions, so your bone could still be horribly placed until you confirm <em>it is not</em>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hL00oSa4WC2l9kVgWEDAPA.gif" /></figure><h4>Extrude Bone</h4><p>Normally, extruding is left for processes such as those at a candy factory where candy is extruded out of a machine and clamped at the correct time to create each piece of candy.</p><p>Today, we will be extruding bone instead. Let’s try it:</p><ul><li>Place a bone where you want it</li><li>Press E</li><li>Move your mouse to place it</li><li>Left Click to complete the creation process</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/755/1*5WrSyz0CJ6kKXNxTz5MMPQ.gif" /><figcaption>Fig X.X — 0% Phallic Reference</figcaption></figure><blockquote><strong>TIP:</strong> Remember, you can Shift + Right Click to select multiple bones and then press G to move them as a group.</blockquote><h4>Naming Bones</h4><blockquote>It’s very important especially on larger and/or more complex models to label your bones.</blockquote><p>To not label your bones would be like naming your variables X1, X2, and X3 rather than Arm, Leg, and Head. You wouldn’t do it. That is to say I wouldn’t do it.</p><blockquote><strong>CRITICAL NOTE</strong>: Since our human model is symmetrical (very bone on the left side is repeated on the right side), we should append .L and .R as we name bones. You never get confused over which Bone you are dealing with.</blockquote><ul><li>In the right-side properties pane, Select Armature</li><li>Check ‘Names’</li><li>In the right-side properties pane, Select Bones</li><li>Type a name into the Name Field</li><li>Press ENTER or Left Click outside the field to save it</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/991/1*jC4Dmgh7wkItoCY6EzK7sQ.gif" /></figure><h4>Bone Creation Order</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/539/1*KYlGdBUm8b_QvqaQ1PQDow.png" /></figure><h3>Control IK Bones</h3><p>IK stands for <strong>Inverse Kinematics</strong>, so these bones will be driven by different physics. From the photo above, we are talking about bone 9 and 10, the wrist and ankle.</p><p>These two bones will have an <strong>IK Constraint</strong>.</p><p>Once you create those two bones:</p><ul><li>Right Click the outer Joint of 5 (Lower Arm.L)</li><li>Hold SHIFT</li><li>Right Click the lower Joint of 7 (Lower Leg.L)</li><li>Press E</li><li>Drag the IK Bones out <strong>parallel with the ground</strong></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/665/1*3BDWOk4dQ3iWnSeEnWMrVg.gif" /></figure><h4>Pole Targets</h4><p>For realistic elbow and ankle movement, we need Pole Targets. These will be Bone 11 and 12, and they complement Bone 9 and 10 to help define movement of the arms and legs.</p><p>A Pole Target is a secondary target for a bone with an IK constraint. The first target is where the chain of bones is trying to get to, and the second target (ie: the Pole Target) is where the chain bends with respect to the Pole Target.</p><h4>Deform</h4><p>To complete the IK Bone creation process, turn off the Deform Property for each IK Bone.</p><p>Do this for:</p><ol><li>Bone 9 (Wrist)</li><li>Bone 10 (Ankle)</li><li>Bone 11 (Elbow)</li><li>Bone 12 (Knee)</li></ol><p>Steps:</p><ul><li>Select a Bone</li><li>In the right-side properties pane, Select Bones</li><li>Uncheck Deform</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/967/1*1MhWiTZ-KL8v23a8FUawMg.png" /></figure><h4>Keep Offset</h4><p>In order for the ankle to rotate correctly, we need to toggle a setting called <strong>Keep Offset</strong>. This will allow us to rotate the foot using the IK Bone.</p><ul><li>Select Bone 8 (Foot)</li><li>Select Bone 10 (Ankle)</li><li>Press CTRL + P</li><li>Select Keep Offset</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/817/1*IMSNrd3V8o9tAIHosuMO2g.gif" /></figure><h4>Pole Constraint with Target</h4><p>If your brain is destroying itself from the inside, don’t worry. I’m pretty sure you will achieve great success just by following my steps even if you have no idea what we are doing or where we are going.</p><p>The next thing we need to do is tie the last few steps together. Our goal is to make the Elbow follow its respective IK Bone, likewise with the Ankle.</p><ul><li>Select Bone 9 (Wrist)</li><li>Select Bone 5 (Lower Arm)</li><li>Enter Pose Mode</li><li>Press CTRL + SHIFT + C to load the Add Constraint (with Target) Menu</li><li>Select Inverse Kinematics</li><li>In the right-side properties pane, Select Bone Constraints</li><li>Select Chain Length: 2</li></ul><blockquote><strong>NOTE</strong>: We selected Chain Length: 2 because the arm has 2 bones in it. We exclude the IK Bone.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3bne0ukkQI8Gsv4wW0lsKw.gif" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/985/1*LJ2vIV0AwqKrJAwvHXeZIw.png" /></figure><p>We have one more critical step to do which instructs the Elbow to follow the Elbow IK Bone.</p><p>You should still be on this screen if you just selected Chain Length: 2, but if not, follow these steps:</p><ul><li>Make sure you’re still in Pose Mode</li><li>Select Bone 5 (Lower Arm)</li><li>Press CTRL + SHIFT + C to load the Add Constraint (with Target) Menu</li><li>Select Inverse Kinematics</li><li>In the right-side properties pane, Select Bone Constraints</li><li>For Pole Target: put Armature</li><li>For Bone: put Bone 11 (Elbow)</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/937/1*g654UCkCz9zyKCbqtkapGA.png" /></figure><p>Now, you should be starting to win wholesale. Let’s stop for a moment and admire what we accomplished:</p><ol><li>When we move the Wrist IK Bone, the arm bends as we might expect;</li><li>When we move the Elbow IK Bone, the elbow follows it and the arm bends as we might expect given that movement;</li><li>Now, when we make animations, it will be impressively easy to achieve life-like movement in only a couple tweens.</li></ol><p>Here is a funky chicken sampler pack:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/904/1*ZKK8UAOX6MwqIE9hM6iAVw.gif" /></figure><p>I recommend taking a break at this point. Get up and walk around — absorb what we just did.</p><p>Now, do the leg:</p><ul><li>Make sure you’re still in Pose Mode</li><li>Select Bone 7 (Lower Leg)</li><li>In the right-side properties pane, Select Bone Constraints</li><li>1 — For Pole Target: put Armature</li><li>2 — For Bone: put Bone 12 (Knee)</li><li>3 — Select Chain Length: 2</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ra6ZLo-fL4a9wkMvR702tw.gif" /></figure><p>Once you do that, lets see how it moves:</p><ul><li>Select the Ankle IK Bone</li><li>Drag the blue arrow to bend the leg up (ie: step up as a human would)</li></ul><p>Wait, it’s completely mangled:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/750/1*TxLDlGVmDJ3itm3mWBQQQg.gif" /></figure><h4>Pole Angle</h4><p>Depending on your model, you have to rotate certain joints.</p><blockquote>Pole Angle is joint rotation in degrees.</blockquote><p>If you would stand up and raise your Knee, you would see that our model is bending his leg approximately 90 degrees in a terrible direction compared to how your leg would move. To fix that:</p><ul><li>Make sure you’re still in Pose Mode</li><li>Select Bone 7 (Lower Leg)</li><li>In the right-side properties pane, Select Bone Constraints</li><li>Click Pole Angle and drag it left/right to approx +90 degrees</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*V3gE7_SOAxKK2k70XQ4w_g.gif" /></figure><p>If we were rigging a spider or something crazy like that, we might select a more wild Pole Angle.</p><p>Take a bonus step back and make sure you can do this movement:</p><ul><li>Select the Ankle IK Bone</li><li>Drag the blue arrow to lift the leg</li><li>Press R while the Ankle IK Bone is selected</li><li>Rotate the ankle up and down</li><li>Press ESC to ditch the rotation control</li><li>Select the Knee IK Bone</li><li>Drag the green arrow to move the knee side-to-side</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/869/1*5K557ri_55snBxD53oZXpA.gif" /></figure><p>You should see something like that in your Blender.</p><h3>Duplicate Bones to Opposite Side</h3><p>Now, we need to select every bone on the left side of the body (ie: everything except the Head, Chest, and Stomach) and duplicate them over to the right side.</p><ul><li>Make sure you’re in Edit Mode</li><li>Press C to get the Brush Selector</li><li>Select all the left side Bones (ie: Exclude Head, Chest, Stomach)</li><li>Press W</li><li>Select Symmetrize</li></ul><p>Boom, done.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/869/1*RAX1Qsqx3QBOMihHkEWdTQ.gif" /></figure><p>The old way to do this in Blender was to select all the bones, then duplicate them with SHIFT + D, then press S, then press X, then hold — and press 1.</p><p>This is kind of a ridiculous sequence, but S, X, — 1 is kind of like a Mortal Kombat cheat code combo. It will flip the new bones over to the opposite side (ie: transform them like in math terms from the positive axis over to the same but negative axis).</p><p>The old way involved clicking Armature at the bottom left area and then selecting Flip Names, but that does not work for our purpose anymore. You can try it and see. It’s harmless after you press CTRL + Z. If you try that for science purposes, look at what happens with the .001 part.</p><blockquote>The new way to duplicate and flip is to press W then select Symmetrize. This does all steps at once: duplicating and renaming L to R.</blockquote><h4>Optional Step — Turn off Display Names</h4><p>You can turn off Bone Names now if you want due to clutter reasons:</p><ul><li>In the right-side properties pane, Select Armature</li><li>Uncheck Names</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nv6rSZ1d6SkHNp1H2UoiwQ.gif" /></figure><h3>Merge Mesh and Armature</h3><ul><li>Make sure you are in Object Mode</li><li>Select the Mesh</li><li>Hold SHIFT and select the Armature (to select both at the same time)</li><li>Press CTRL + P to get the ‘Set Parent To’ Menu</li><li>Select ‘With Automatic Weights’</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/869/1*mE_xqh8I83H-bm4t5K7Ytg.gif" /></figure><p>You are probably noticing that we have some deformities sprinkled illegally in some areas. This is due to anomaly with Bone Constraints. Let’s fix that:</p><ul><li>Make sure you are in Pose Mode</li><li>Right Click the problematic Bone (in this case, Lower Arm.R)</li><li>In the right-side properties pane, Select Bone Constraints</li><li>Adjust the Pole Angle (in this case, to about +100 degrees)</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6TUYd9zbW0tkFuOGdStazQ.gif" /></figure><blockquote><strong>NOTE</strong>: if you ever see Bones exhibiting crazy weird movement symptoms, consider the Pole Angle first.</blockquote><p>If you flip back and forth between Pose Mode and Edit Mode, you can what might need to be changed.</p><h3>Torso Control</h3><p>Our character needs to have better movement for the torso. To achieve that, we will connect the Upper Arms and Upper Legs to the bottom of torso (ie: the Stomach Bone).</p><ul><li>Make sure you are in Edit Mode</li><li>Select the Upper Left Arm</li><li>Press and hold SHIFT</li><li>Select the Upper Right Arm</li><li>Select the Upper Left Leg</li><li>Select the Upper Right Leg</li><li>Select the Stomach Bone last</li><li>Let go of SHIFT</li><li>Press CTRL + P to access the ‘Make Parent’ Menu</li><li>Select ‘Keep Offset’</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/833/1*tbjyIalLfFZmigrXPpIKtA.gif" /></figure><p>As we can now see, the movement of the character is extremely realistic:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jRKl8Zr0K7kempqORuHsdQ.gif" /></figure><h3>Control Bone</h3><p>We should put in a Bone that controls the entire body:</p><ul><li>Make sure you are in Edit Mode</li><li>Press SHIFT + C to center the cursor</li><li>Press SHIFT + A to create a new Bone</li><li>Right Click the new Bone</li><li>Press R</li><li>Type -90 or -120 or freely rotate the Bone around to where you want it</li><li>You want it facing straight forward from the character’s perspective</li></ul><blockquote><strong>BONUS TIP</strong>: Scroll to the top of this Article if you forget how to move Bones.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VUgECUFVsJ8gj0FVJEGNMg.gif" /></figure><h4>Label Control Bone</h4><ul><li>Right Click the Control Bone</li><li>In the right-side properties pane, Select Bone</li><li>Type in ‘Control’ or whatever you prefer</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*K1hxR_yKI4Kl6fSR1ER-Fw.gif" /></figure><h4>Make Control Bone the Root Parent</h4><p>Now, lets connect this new Bone to the current master parent Bone (the Stomach Bone) with some new familiar steps:</p><ul><li>Make sure you are in Edit Mode</li><li>Right Click to select the Stomach Bone first</li><li>Hold SHIFT to multi-select</li><li>Right Click the Control Bone</li><li>Let go of SHIFT</li><li>Press CTRL + P to access the ‘Make Parent’ Menu</li><li>Select ‘Keep Offset’</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/812/1*FDU5Yj-ppUqXAXOk01Mh8w.gif" /></figure><h4>Attach IK Bones to Control Bone</h4><ul><li>Hold SHIFT and select all 8 IK Bones</li><li>While holding SHIFT, select the Control Bone last</li><li>Let go of SHIFT</li><li>Press CTRL + P to access the ‘Make Parent’ Menu</li><li>Select ‘Keep Offset’</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/812/1*a5lxV27-PYPBbc81zIDY9Q.gif" /></figure><p>Looks good.</p><h4>Optional Step — Turn off Relationship Lines</h4><ul><li>Press N</li><li>In this opened right side pane, scroll down to ‘Display’</li><li>Uncheck ‘Relationship Lines’</li></ul><h3>Custom Control Shapes</h3><p>If you would like to utilize custom shapes for extra-rad controls, check out these steps:</p><ul><li>Select a New Layer at the bottom</li><li>Press SHIFT + A</li><li>Under ‘Mesh’, select ‘Circle’</li><li>Enter Edit Mode</li><li>Put the cursor in the middle of the Circle</li><li>Press E then S then drag the outer part of the Circle inward a bit (to give the Circle a bit of thickness)</li><li>Press SHIFT + A again</li><li>Under ‘Mesh’ again, select ‘UV Sphere’</li><li>Done</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/823/1*Lphl1yE23ttDWq37hAZ7Dg.gif" /></figure><blockquote><strong>Note</strong>: New Layer is here at the bottom:</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/968/1*8VwkicRvJADPWYV-65_njA.png" /></figure><p>Now, go back to the first Layer where our character is.</p><ul><li>Make sure you are in Pose Mode</li><li>Select an Elbow or Knee Bone</li><li>In the ride side properties pane, under Bone, select ‘Custom Shape’</li><li>Select ‘Sphere’</li><li>Fancy</li><li>Do the rest of the spheres too</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JPW8FcxBdp5YC7porGzykQ.gif" /></figure><p>You will notice the spheres are probably a bit too large. No problem:</p><ul><li>Right Click a sphere</li><li>Below Custom Shape in the right side properties pane, change the scale</li><li>I set mine to 0.3 (30% of the original size)</li><li>Pick a number you like</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QUM2Mf4Xdos0Jwt_Mn3v9Q.gif" /></figure><p>For the Control Bone, we can select the Circle:</p><ul><li>Right Click the Control Bone</li><li>In the right side properties pane, select Custom Shape</li><li>Select Circle</li><li>Ultra pro style, complete</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lqFuDifT4wb_TTBrjtmFlg.gif" /></figure><h3>Turn Off Unused Bones</h3><p>Most of the bones we made we will never manipulate under normal circumstances, so we should hide those bones:</p><ul><li>Make sure you are in Pose Mode</li><li>Select all Arm Bones (2 in total)</li><li>Select all Leg Bones (4 in total)</li><li>Select both Feet Bones (2 in total)</li><li>Press M to move them to another Skeleton Layer</li><li>Select a new layer, such as second row first slot</li><li>Done</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*w8LBzpnLyIHS1bJVvRjhkw.gif" /></figure><p>If you want to see those hidden Bones again:</p><ul><li>In the right side properties pane, select Armature</li><li>Under Skeleton Layers, notice the two layers</li><li>Click the second layer</li><li>Click the first layer again (just to see the two layers separately)</li><li>Now, hold SHIFT and select both layers</li><li>Boom, now both are displayed at the same time</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sjLfMwHr6nt6tB7aT_ZF8Q.gif" /></figure><h3>Conclusion</h3><p>And with that, we are done.</p><p>I suggest going through this process a few times on separate days to really commit everything to muscle memory. Blender hot keys are a bit nasty. That’s why I made this tutorial. I will probably need it again soon.</p><p>Follow me on Twitter to stay in the JavaScript render loop:</p><p><a href="https://www.twitter.com/agm1984"></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=846e258a9d9d" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>