<?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 Kyle Ledoux on Medium]]></title>
        <description><![CDATA[Stories by Kyle Ledoux on Medium]]></description>
        <link>https://medium.com/@kaledoux?source=rss-b68c7c52653b------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*e2e0ku6s4KGXUgjMxesi_A.jpeg</url>
            <title>Stories by Kyle Ledoux on Medium</title>
            <link>https://medium.com/@kaledoux?source=rss-b68c7c52653b------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 23 Nov 2026 23:42:25 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@kaledoux/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[Elixir — A Tincture for Functional Programming Part 1.6 Comprehensions]]></title>
            <link>https://kaledoux.medium.com/elixir-a-tincture-for-functional-programming-part-1-6-comprehensions-5215d63c6816?source=rss-b68c7c52653b------2</link>
            <guid isPermaLink="false">https://medium.com/p/5215d63c6816</guid>
            <category><![CDATA[syntactic-sugar]]></category>
            <category><![CDATA[functional-programming]]></category>
            <category><![CDATA[elixir]]></category>
            <dc:creator><![CDATA[Kyle Ledoux]]></dc:creator>
            <pubDate>Mon, 21 Feb 2022 18:21:53 GMT</pubDate>
            <atom:updated>2022-02-21T18:21:53.015Z</atom:updated>
            <content:encoded><![CDATA[<h3>Elixir — A Tincture for Functional Programming Part 1.6 Comprehensions</h3><h3>Comprehensions</h3><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2FkVVEP6SmfEXvy%2Ftwitter%2Fiframe&amp;display_name=Giphy&amp;url=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2FkVVEP6SmfEXvy%2Fgiphy.gif&amp;image=https%3A%2F%2Fi.giphy.com%2Fmedia%2FkVVEP6SmfEXvy%2Fgiphy.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="314" frameborder="0" scrolling="no"><a href="https://medium.com/media/5a4151d58749b1c4e9a4647e3a3194c8/href">https://medium.com/media/5a4151d58749b1c4e9a4647e3a3194c8/href</a></iframe><h4>Just A Bit of Sugar</h4><p>In a <a href="https://kaledoux.medium.com/elixir-a-tincture-for-functional-programming-part-1-5-recursion-ec24b0e1097f">previous article</a>, I did a quick tour of recursion in Elixir, and why it is important in Elixir, but also as a staple of Functional Programming. Therein, we talked about why operations that require repetition and mutation of values (like a Ruby while x do loop) don’t work in Elixir because all values are immutable.</p><p>However, there is a little bit of syntactical sugar in Elixir that provides the same functionality and a similar syntax the the above, providing a clean, useful abstraction for common behaviors that involve looping over enumerables.</p><p>This functionality is provided through the special form for(args) into which comprehensions group common looping constructs.</p><blockquote><strong>Comprehensions are the syntactic sugar for common looping constructs</strong></blockquote><p>These comprehensions allow you to take an enumerable and quickly build a new data structure with common looping constructs like mapping (transformation) or filtering (selection).</p><p>The syntax isn’t too tricky, so let’s take a quick look.</p><h4>Generators and Pattern Matching</h4><p>The basic syntax for using the special form for is as follows:</p><blockquote><em>for</em> <strong>generator</strong> <em>do</em> <strong>block</strong></blockquote><p>In a simple example we can use this format to iterate through a list of numbers and find the squares of each value, mapping to a new list:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/43d7a4a225e244e0a793ed0e5321d7ba/href">https://medium.com/media/43d7a4a225e244e0a793ed0e5321d7ba/href</a></iframe><p>The <strong>generator</strong> is <em>an expression which is used to generate values</em> that are used in the comprehension. The nifty thing about generators is that you can pass any type of enumerable to it and it will work just the same:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/670b5959ffca378e0351d664c3bdbd48/href">https://medium.com/media/670b5959ffca378e0351d664c3bdbd48/href</a></iframe><p>Another really cool part about generator expressions is that they <em>support pattern matching</em>. Not just that, but <em>values that do not fit the pattern matching operation are</em><strong> <em>ignored</em></strong>, and not even passed to the block!</p><p>Let’s see how this might work:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0259430c01a9bf92cda426a6e1d73e5e/href">https://medium.com/media/0259430c01a9bf92cda426a6e1d73e5e/href</a></iframe><p>Pretty cool, right?</p><h4>Let’s filter</h4><p>On top of using generator expressions, we can also pass in one, or many, filtering expressions that we can use to abstract away the process of filtering our collection as well.</p><p>All you need to do is pass in additional arguments to for ; these expressions should return booleans values, but for will discard any value that returns falsy.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ee0ff6087c3e41c458b070b7a7ff4cfd/href">https://medium.com/media/ee0ff6087c3e41c458b070b7a7ff4cfd/href</a></iframe><p>A very handy aspect, as mentioned, is that <em>you can use multiple filter expressions in sequence</em>, making a tidy way to filter down a collection!</p><h4>Conclusion</h4><p>This only details the basic usage of the special form for, there are many other cool ways to use it with btistrings, as well as options like :into, :uniq, and :reduce which add functionality and improve performance.</p><p>If you would like to learn more about those functions, I highly recommend reading through the <a href="https://gist.github.com/kaledoux/e3baf4d6e3af1c2f43787b64b07d2e00">docs</a>, as these will give you the best information for adding that sweet, sweet sugar to your programs!</p><figure><img alt="lumps of sugar" src="https://cdn-images-1.medium.com/max/700/1*PygWhjyEpFtX-YnDtd3VUw.jpeg" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5215d63c6816" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Elixir — A Tincture for Functional Programming Part 1.5 Recursion]]></title>
            <link>https://kaledoux.medium.com/elixir-a-tincture-for-functional-programming-part-1-5-recursion-ec24b0e1097f?source=rss-b68c7c52653b------2</link>
            <guid isPermaLink="false">https://medium.com/p/ec24b0e1097f</guid>
            <category><![CDATA[recursion]]></category>
            <category><![CDATA[functional-programming]]></category>
            <category><![CDATA[elixir]]></category>
            <dc:creator><![CDATA[Kyle Ledoux]]></dc:creator>
            <pubDate>Mon, 14 Feb 2022 20:28:02 GMT</pubDate>
            <atom:updated>2022-02-17T16:25:23.934Z</atom:updated>
            <content:encoded><![CDATA[<h3>Elixir — A Tincture for Functional Programming Part 1.5 Recursion</h3><h3>Recursion</h3><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2F3ov9jQX2Ow4bM5xxuM%2Ftwitter%2Fiframe&amp;display_name=Giphy&amp;url=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2F3ov9jQX2Ow4bM5xxuM%2Fgiphy.gif&amp;image=https%3A%2F%2Fi.giphy.com%2Fmedia%2F3ov9jQX2Ow4bM5xxuM%2Fgiphy.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="353" frameborder="0" scrolling="no"><a href="https://medium.com/media/eaf72562f5104522401a25c60f11532c/href">https://medium.com/media/eaf72562f5104522401a25c60f11532c/href</a></iframe><h4>Why Recursion is important in Elixir</h4><p>Recursion is important in Elixir because we <strong>cannot mutate the state</strong> of any values in Elixir.This means that any operation that <em>requires repetition</em> and mutating a value, is not viable in Elixir.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/416d5b2ad1bf126f92c18d9f7c96b4c8/href">https://medium.com/media/416d5b2ad1bf126f92c18d9f7c96b4c8/href</a></iframe><p>These examples are not possible in Elixir, as written, because they depend on the variables being mutated. For Elixir, we need to turn to recursion if we want to achieve similar repetitive tasks.</p><blockquote><strong>Note</strong>: Elixir does provide the use of <a href="https://elixir-lang.org/getting-started/comprehensions.html">comprehensions</a>, which are an added piece of syntactical sugar to create code block similar to the for x in collection style of repetition. This is just syntactical sugar (albeit very handy syntactical sugar) and there is no variable mutation occurring under the hood. So, bearing that in mind we’ll focus on the recursive solutions herein as they are a hallmark of Functional Programming.</blockquote><h4>Making Sure It Stops</h4><p>Recursion in Elixir is no different than recursion in any other programming language in that <em>it is critically important to </em><strong><em>identify</em></strong><em> the case which will bring the recursive call to </em><strong><em>an end</em></strong>.</p><p>Without this end clause, stack overflows and CTRL+Cawaits you.</p><figure><img alt="Ouroboros" src="https://cdn-images-1.medium.com/max/800/1*L3dEyfEQcthnR-B-wxOo2g.jpeg" /></figure><p>The ending function clause <em>needs to be defined before the other clauses</em>, because Elixir will execute the first matching function clause that it finds for a function definition (remember short circuiting).</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/86eaecde34e61c09579ad4fede3a44c2/href">https://medium.com/media/86eaecde34e61c09579ad4fede3a44c2/href</a></iframe><h4>Where Recursion Shines in Elixir — Lists</h4><p>One of the most useful uses of recursion in Elixir, is the iteration, transformation, and selection of lists.</p><p>All based on the use of [head | tail]to extract the head node of the current list, act on it and pass the tail (see: the remaining list nodes) to a recursive function call. We can leverage the syntax feature of creating new lists by using this same [head |tail] syntax to append a new node onto a list (which is faster than appending to the list).</p><p>[:a | [:b, :c, :d] ~~~&gt; [:a, :b, :c, :d]</p><p><strong>Iteration</strong>:</p><p>Here we can see how we can construct a basic set of functions show_cheese to iterate through all the nodes of a list (and print to the screen just for demo purposes).</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e44e637b54c70a0a797d483c98150490/href">https://medium.com/media/e44e637b54c70a0a797d483c98150490/href</a></iframe><p><strong>Transformation</strong>:</p><p>If we want to transform each element in the list, we can also do that with our change_cheese functions. The key here is to return a new list that leverages the recursive function call within the return value.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4bd5a1de06d2d9df6f552f74f76ba45f/href">https://medium.com/media/4bd5a1de06d2d9df6f552f74f76ba45f/href</a></iframe><p><strong>Selection</strong>:</p><p>To return a new list that only contains values that match some set of criteria we provide, we can do that as well with one extra conditional block. select_cheese shows how we can do this pretty easily.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c2b001975ec623503a30bb08a3a8a32d/href">https://medium.com/media/c2b001975ec623503a30bb08a3a8a32d/href</a></iframe><h4>Modules to the Rescue</h4><p>Now that we have covered how to create basic <em>iteration</em>, <em>transformation</em>, and <em>selection</em> methods for lists, I’ll share a secret:</p><blockquote>There are built in modules in Elixir that abstract away the need to hard code this functionality yourself!</blockquote><p>The <a href="https://hexdocs.pm/elixir/1.13/Enum.html">Enum</a> module in Elixir contains methods that can accomplish these operations, plus a host of other useful ones as well, so before you go reinventing the wheel, make sure that operation is not already covered!</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8d7d287a628655797b6463620f0a0bb0/href">https://medium.com/media/8d7d287a628655797b6463620f0a0bb0/href</a></iframe><h4>Conclusion</h4><p>There are other features of recursion in Elixir like tail-call optimization and work with streams that I may tackle later, but don’t be afraid to start working through recursion on your own!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ec24b0e1097f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Elixir — A Tincture for Functional Programming Part 1.4 Pattern Matching]]></title>
            <link>https://kaledoux.medium.com/elixir-a-tincture-for-functional-programming-part-1-4-pattern-matching-679889088411?source=rss-b68c7c52653b------2</link>
            <guid isPermaLink="false">https://medium.com/p/679889088411</guid>
            <category><![CDATA[destructuring]]></category>
            <category><![CDATA[functional-programming]]></category>
            <category><![CDATA[pattern-matching]]></category>
            <category><![CDATA[elixir]]></category>
            <dc:creator><![CDATA[Kyle Ledoux]]></dc:creator>
            <pubDate>Tue, 08 Feb 2022 22:13:47 GMT</pubDate>
            <atom:updated>2022-02-08T22:13:47.305Z</atom:updated>
            <content:encoded><![CDATA[<h3>Elixir — A Tincture for Functional Programming Part 1.4 Pattern Matching</h3><h3>Pattern Matching</h3><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2FdESOVXFDsP1ZK%2Ftwitter%2Fiframe&amp;display_name=Giphy&amp;url=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2FdESOVXFDsP1ZK%2Fgiphy.gif&amp;image=https%3A%2F%2Fi.giphy.com%2Fmedia%2FdESOVXFDsP1ZK%2Fgiphy.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="244" frameborder="0" scrolling="no"><a href="https://medium.com/media/84397900574a01edce2b76062fdde766/href">https://medium.com/media/84397900574a01edce2b76062fdde766/href</a></iframe><h4>Intro</h4><p>One concept that I found initially tricky to understand was that of pattern matching. In Elixir, I found that the humble `=` operator does much more than simple assignment. It also provides useful pattern matching functionality that is extremely helpful when destructuring parts of values. Pattern matching also plays a large role in control flow in functional languages, largely taking the place of common control flow idioms like `if/else` statements.</p><p>So, knowing that the `=` operator plays an important role in pattern matching, and further, that pattern matching plays an important role in dictating control flow in functional programming, what exactly is it?</p><h4>What is pattern matching in Elixir?</h4><p>Before getting into the “fun” stuff that we can do with pattern matching, it is helpful to loosely define what pattern matching is in Elixir. As Ulisses Almeida succinctly states:</p><blockquote>The basis of pattern matching is that it tries to make two things match, and it does something when it fails to do so.</blockquote><p>The =operator will perform a pattern match, trying to match the value of the expression on the left with the value of the expression on the right. If there is a match, then the program continues to run, if there is no match, then Elixir will raise a MatchError and halt program execution.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/844799c22bbed8ecc3064268c6bae711/href">https://medium.com/media/844799c22bbed8ecc3064268c6bae711/href</a></iframe><p>Variable assignment is a form of pattern matching; Elixir is making the value on the left (the variable) match the value on the right. When a variable is given on the left of the =operator, Elixir will bind it to the value on the right.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a69bec5120c427481e4415e63cb576c7/href">https://medium.com/media/a69bec5120c427481e4415e63cb576c7/href</a></iframe><h4>Pin it!</h4><p>If you have set a variable to a certain value and do not want to reassign it, but rather try to perform a pattern match with it, you can prefix the variable name with the ^pin operator.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/406f5792aa880c85949dea30da469738/href">https://medium.com/media/406f5792aa880c85949dea30da469738/href</a></iframe><h4>Destructuring</h4><p>The most interesting use for pattern matching that I have encountered so far is destructuring. Using variables and pattern matching, we can extract specific elements from different types of values. Here are a few value types that I have found most helpful when destructuring.</p><p><strong>List</strong>:</p><p>For pattern matching with <a href="https://hexdocs.pm/elixir/List.html">Lists</a> we use [].</p><p>The most useful form of pattern matching destructuring with lists uses the [head | tail] syntax. This will extract the first value in the list to the variable head and assign the remaining list to the variable tail.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c0761adaf2f37c5b1510d9917675408b/href">https://medium.com/media/c0761adaf2f37c5b1510d9917675408b/href</a></iframe><p>Destructuring like this is invaluable in iterating through and transforming lists.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/84113590381f169779c89d353752d8c1/href">https://medium.com/media/84113590381f169779c89d353752d8c1/href</a></iframe><p>There are other forms of List pattern matching as well. We can use a pattern of variables to verify that the corresponding values in the list follow the same pattern. Or we can ignore parts of the list by using the _wildcard character. This will match any corresponding value in the collection.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0a7dab11cec941bb163ba253b62b81dd/href">https://medium.com/media/0a7dab11cec941bb163ba253b62b81dd/href</a></iframe><p><strong>Map</strong>:</p><p>Using pattern matching we can easily grab values from a <a href="https://hexdocs.pm/elixir/1.13/Map.html">Map</a> and assign it to a variable while checking values for matches.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3ab631d93a49e5ab36a1e21f9e5cf511/href">https://medium.com/media/3ab631d93a49e5ab36a1e21f9e5cf511/href</a></iframe><p><strong>String</strong>:</p><p>Using pattern matching can be a handy trick with Strings to extract key bits from a larger value. Use the &lt;&gt;operator to check the beginning of a string:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3d90d738517724a76305aee18b73e2ff/href">https://medium.com/media/3d90d738517724a76305aee18b73e2ff/href</a></iframe><p>Remember that the variable cannot be placed on the left of the &lt;&gt;operator or an error will be raised!</p><h4>Further Reading</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*jiUNuBgOBDbXUUA46nFPRA.jpeg" /></figure><p>There is plenty more to learn about pattern matching including how to do so with additional value types and how to use them for control flow, among other things. If you want to learn more, I’d suggest reading the relevant sections in <a href="https://joyofelixir.com/6-pattern-matching">The Joy of Elixir</a> and <a href="https://learning.oreilly.com/library/view/learn-functional-programming/9781680505757/">Learn Functional Programming with Elixir</a> for some great explanations with easy-to-understand examples.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=679889088411" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Elixir — A Tincture for Functional Programming Part 1.3]]></title>
            <link>https://kaledoux.medium.com/elixir-a-tincture-for-functional-programming-part-1-3-eec48ebe509b?source=rss-b68c7c52653b------2</link>
            <guid isPermaLink="false">https://medium.com/p/eec48ebe509b</guid>
            <category><![CDATA[closure]]></category>
            <category><![CDATA[lexical-scoping]]></category>
            <category><![CDATA[elixir]]></category>
            <category><![CDATA[functional-programming]]></category>
            <dc:creator><![CDATA[Kyle Ledoux]]></dc:creator>
            <pubDate>Thu, 03 Feb 2022 17:02:41 GMT</pubDate>
            <atom:updated>2022-02-08T22:14:20.975Z</atom:updated>
            <content:encoded><![CDATA[<h3><strong>Elixir — A Tincture for Functional Programming Part 1.3 Closures</strong></h3><figure><img alt="a magical elixir from a well know game series" src="https://cdn-images-1.medium.com/max/250/1*DFJlYDiTvrqIqwrg_LPVlw.jpeg" /></figure><h3>Understanding Closures</h3><p>This time around I’ll be talking about closures in Elixir. The topic of closures can be tricky to get your head around if you are unfamiliar with the concept, but I’ll do my best to give a quick rundown here of what they are and how they function within Elixir.</p><h4>What’s a closure?</h4><p>The concepts of closures are not unique to Elixir and chances are you have encountered them in other languages whether you knew it or not.</p><p>A <strong>closure </strong>is a <em>combination of a function’s definition and references to its surrounding state</em><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Closures">1</a>. So, a function, when it is defined, will maintain references to the variables that are defined in its surrounding scope so that it can reference and utilize those variables during invocation. In plain English, this basically means that the function can still “see” the variables in its outer scope, even if it is invoked elsewhere in the program.</p><h4>Scoping. Explain this please.</h4><p>Scoping in a program commonly works in one of two ways: dynamically or lexically.</p><p>Lexical scoping is the method of scoping that Elixir and most other languages use. With <strong>lexical scoping </strong>the variables that a function has access to when it is invoked is determined by <em>where the function is defined</em>.</p><p>With <strong>dynamic scoping</strong>, the variables that a function has access to is determined by <em>where the function is invoked</em>.</p><p>So, with Elixir, we are using lexical scoping, and to understand which variables a function will have access to, we need to look at the code where it is <em>defined</em>, not invoked!</p><h4>Bottoms up!</h4><p>Closures in Elixir work on the basis of lexical scoping, so we need to know what the code looks like where the function was defined to understand what variables it can access when it is invoked. In Elixir, functions will have visibility of all variables that are defined above them, and within their outer scope. This is referred to as the function’s <em>upward scope</em>.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e9f0112af438f7a08178e3754d21b56a/href">https://medium.com/media/e9f0112af438f7a08178e3754d21b56a/href</a></iframe><p>When the compiler encounters a function definition containing a reference to variable, it will <em>scan upwards</em> for the referenced variable and <strong><em>match the first occurrence</em></strong> that it finds.</p><p>So, the assignment closest to the function and above it, while remaining in its outer scope, will be used.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3689005bcc0f0d7a19714db5999f434c/href">https://medium.com/media/3689005bcc0f0d7a19714db5999f434c/href</a></iframe><p>Here we can see that variables that are <em>not in the function definition’s outer scope</em> will <strong>not be visible</strong> in the closure (obviously):</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a4ca7c95fb1599fb34d7a2a47723c551/href">https://medium.com/media/a4ca7c95fb1599fb34d7a2a47723c551/href</a></iframe><h4>That’s cool. But, why?</h4><p>Using closures allows us to pass values to a function without having to worry about doing so explicitly during invocation. So, if the function is <em>invoked asynchronously</em>, for example, we can make sure that it still has visibility for variables that it might need.</p><p>Here is a contrived example where some function is called asynchronously by another function to generate a report using some status codes. But, we don’t need to worry about being able to pass in the status codes as arguments when the function is invoked because they are accessible via closure:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9090fe28217eb437173c82a0670b399e/href">https://medium.com/media/9090fe28217eb437173c82a0670b399e/href</a></iframe><p>Closures are interesting and can come into play in interesting ways. I’m sure there is a great deal more to discover here, so I’ll keep working!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=eec48ebe509b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Elixir — A Tincture for Functional Programming Part 1.2]]></title>
            <link>https://kaledoux.medium.com/elixir-a-tincture-for-functional-programming-part-1-2-4bb8d90419d9?source=rss-b68c7c52653b------2</link>
            <guid isPermaLink="false">https://medium.com/p/4bb8d90419d9</guid>
            <category><![CDATA[function]]></category>
            <category><![CDATA[functional-programming]]></category>
            <category><![CDATA[lambda]]></category>
            <category><![CDATA[elixir]]></category>
            <category><![CDATA[first-class-function]]></category>
            <dc:creator><![CDATA[Kyle Ledoux]]></dc:creator>
            <pubDate>Wed, 02 Feb 2022 20:28:52 GMT</pubDate>
            <atom:updated>2022-02-08T22:14:46.701Z</atom:updated>
            <content:encoded><![CDATA[<h3>Elixir — A Tincture for Functional Programming Part 1.2 Functions</h3><h3>Fun with Functions</h3><p>As I continue to learn about and work with Elixir, more and more interesting tidbits continue to surface. Some of these are related to Functional Programming itself and others are specific to the language of Elixir. But, if I find it interesting and/or useful, I will write about it in this series that loosely follows my progress.</p><figure><img alt="large lego blocks being placed down in a stack" src="https://cdn-images-1.medium.com/max/1024/1*bkGqbtZnt1WegBOEzCnFzA.jpeg" /></figure><h4>Legos</h4><p>This time around, I get into some more substantial Elixir: working with Functions. After all, <em>they are the building blocks of all programs</em> in Functional Programming, so it’s important to have a good baseline for how functions work in Elixir.</p><p>In the Functional Programming paradigm, we construct our programs not using a bevy of objects that carry state and a set of methods that interact with those internal states as we might when working with Object Oriented Programming, but rather with a set of functions that have no functional dependencies resulting from internal state.</p><p>Functions in Elixir do three things:</p><ol><li>Take data</li><li>Operate on the data</li><li>Return some values</li></ol><p>We construct Elixir programs using short, simple functions that build on one another to create a data transformation pipeline. This circumvents many internal state dependency problems but also has the benefit of making programs easy to understand and maintain!</p><h4>A Good Name</h4><p>There are different types of functions in Elixir, but I have found it easy to break them into two very broad categories: <strong>named </strong>and <strong>anonymous</strong>.</p><p>Named functions are <em>defined inside modules</em> in Elixir. We can create our own modules and define named functions inside them for later reuse.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/82e7ed2a7fa23c8a721a98e2fd4dac2f/href">https://medium.com/media/82e7ed2a7fa23c8a721a98e2fd4dac2f/href</a></iframe><p>Elixir does have a host of useful named functions that we can leverage to accomplish a wide range of tasks.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f836c1ce5b9c306e70c4bcdcba5488a1/href">https://medium.com/media/f836c1ce5b9c306e70c4bcdcba5488a1/href</a></iframe><p>There are a bunch, and you can probably find one that will cover most any simple task you encounter. Check <a href="https://hexdocs.pm/elixir/Kernel.html">here</a> to find the different modules and the named functions they provide!</p><h4>Lambdas Everywhere</h4><p>In addition to defining and utilizing named functions in Elixir, we can also create Anonymous Functions, also known as lambdas.</p><p>Anonymous functions are so called because they have <em>no global name</em> and to use them, you <em>must assign them to a variable</em>.</p><p>Defining them is relatively simple, we just need to use the special form for doing so with the `fn` and `end` keywords. Special forms in Elixir cannot be overridden, so we know that this format should also work as we expect it to:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1e8fa00d750840232b9b10411a5bf793/href">https://medium.com/media/1e8fa00d750840232b9b10411a5bf793/href</a></iframe><h4>Extra Legroom</h4><p>One last interesting feature of functions in Elixir is that they are treated as first-class citizens. This means that they can be passed into other functions as arguments. This is because all functions are values of type `function`, so they can be passed in and utilized in a function call.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6de3f1fcd76c493c0f60dc14d14231d3/href">https://medium.com/media/6de3f1fcd76c493c0f60dc14d14231d3/href</a></iframe><p>This is really useful for adhering to the tenets of Functional Programming and creating declarative code:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7e88df6ec99b1557f1fb021fb0ddfb85/href">https://medium.com/media/7e88df6ec99b1557f1fb021fb0ddfb85/href</a></iframe><p>That’s it for now! Go have some fun with functions!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4bb8d90419d9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Elixir — A Tincture for Functional Programming]]></title>
            <link>https://kaledoux.medium.com/elixir-a-tincture-for-functional-programming-e49b6bf6ede4?source=rss-b68c7c52653b------2</link>
            <guid isPermaLink="false">https://medium.com/p/e49b6bf6ede4</guid>
            <category><![CDATA[declarative-programming]]></category>
            <category><![CDATA[dynamic-programming]]></category>
            <category><![CDATA[functional-programming]]></category>
            <category><![CDATA[elixir]]></category>
            <dc:creator><![CDATA[Kyle Ledoux]]></dc:creator>
            <pubDate>Tue, 01 Feb 2022 20:14:28 GMT</pubDate>
            <atom:updated>2022-02-08T22:15:17.241Z</atom:updated>
            <content:encoded><![CDATA[<h3>Elixir — A Tincture for Functional Programming 1.1 What is FP?</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/280/1*CBkzNFhl20vyAXyWzpklSg.png" /></figure><h3>Intro</h3><p>Elixir was unknown to me prior to a few weeks ago when I was made aware that my new team worked with a few microservices that were built with Elixir. Not having any knowledge of or experience with it up until then, I soon realized that I would need to do some learning. My programming experience was entirely in the realm of Object-Oriented Programming, and after dipping my toes into the water with a few basic problems, it became clear that I wasn’t just going to improvise my way through. There are some significant differences with Object-Oriented Programming and honestly, some really great features that are worth knowing.</p><p>So, I am writing about Elixir to detail some of the more interesting features of the language and functional programming that I come across as I continue my learning journey with Elixir and Functional Programming. I am not an expert, so always defer to documentation if there is a discrepancy.</p><blockquote>I have been working with a few different sources of learning material, all of which are great. Check them out:</blockquote><blockquote><a href="https://elixir-lang.org/">Elixir Docs</a></blockquote><blockquote><a href="https://pragprog.com/titles/cdc-elixir/learn-functional-programming-with-elixir/">Learning Functional Programming with Elixir</a></blockquote><blockquote><a href="https://joyofelixir.com/">Joy of Elixir</a></blockquote><h3>What is Elixir?</h3><p>Elixir is a <em>dynamic language</em> that uses <em>functional programming</em> paradigms and leverages the <em>Erlang VM</em>.</p><p><strong>Dynamic languages</strong> are those in which the types of values are determined at runtime, meaning that the type of a variable does not need to be explicitly stated during compilation. A dynamic program can run with type errors compiled but it will raise an exception during runtime. Static languages on the other hand must have types set prior to runtime and will fail to compile if any type errors are detected.</p><p>Let’s see a basic example of dynamic typing in Ruby:</p><pre>### squid_game.rb</pre><pre># initialize a variable with an implicit type of string<br>squids_in_tank = &quot;sepia lycidas&quot;<br># then try to perform some operation that requires a different type<br>squids_in_tank -= 1</pre><pre>puts squids_in_tank<br>###</pre><pre># run the program<br>ruby squid_game.rb<br>#=&gt; NoMethodError on &quot;sepia lycidas&quot; type String</pre><p>We can run the program, but it errors out at runtime due to typing errors. If we look to a statically typed language like GO, we can try to do the same thing, but because we explicitly declare the type of the variable and the compiler checks its related operations, it will error out during compile time, not run time:</p><pre>// squid_games.go //<br>package main</pre><pre>func main() {<br> var squids_in_tank string = &quot;sepia lycidas&quot;<br> squids_in_tank -= 1<br>}<br>// </pre><pre>go run squid_games.go<br>//=&gt; Invalid Operation during compile</pre><p><strong>Functional programming</strong> is a programming paradigm; it follows a set of best practices for writing code and designing programs. It differs from Object Oriented Programming in important ways, which we will detail later.</p><p><strong>Elixir uses Erlang and the Erlang VM</strong>, which is built for scalability and concurrent processing. The Erlang VM uses one Erlang process/thread per core and has a host of other features that make it great for work with parallel processing and distributed systems. This article does a great job at breaking down <a href="https://blog.lelonek.me/elixir-on-erlang-vm-demystified-320557d09e1f">how the Erlang VM works</a>.</p><h3>Brewing up a new point of view</h3><p>A huge part of my early difficulties with Elixir stemmed from my ignorance of functional programming paradigms, so it is really important to answer the question:</p><blockquote>What is Functional Programming?</blockquote><p>Coming from a world of Object-Oriented Programming, functional programming is a bit of a mental shift. The paradigm carries different views on how to program and what priorities are in program design. There are a few core concepts that are key to making sense of the Functional Programming paradigm.</p><h4>Core Concept 1: Say WHAT you want, not HOW you want it done!</h4><p>The first is that the method of programming utilized in Functional Programming is <em>declarative programming, </em>instead of imperative programming. But what does that mean?</p><p><strong>In a nutshell, we tell Elixir <em>what</em> we want done, instead of exactly <em>how</em> to do it</strong></p><p>Ruby — prepending some text imperatively</p><pre># in Ruby we lay out exactly HOW we want the names to be modified<br>squid_names = [&#39;sepia esculenta&#39;, &#39;common cuttlefish&#39;, &#39;sepia lycidas&#39;]</pre><pre>for ind in (0..squid_names.length - 1) do<br>  prefix = &quot;~~~~~~&quot;<br>  new_name = prefix + squid_names[ind]<br>  squid_names[ind] = new_name<br>end</pre><pre>p squid_names<br>#=&gt;[&quot;~~~~~~sepia esculenta&quot;, &quot;~~~~~~common cuttlefish&quot;, &quot;~~~~~~sepia lycidas&quot;]</pre><p>Elixir — prepending some text declaratively</p><pre># in Elixir we describe WHAT we want the names to be modified to<br>defmodule SquidNames do<br>  def names, do:  [&quot;sepia esculenta&quot;, &quot;common cuttlefish&quot;, &quot;sepia lycidas&quot;]</pre><pre>  def prefix([]), do: []<br>  def prefix([name | others]) do<br>    padded_length = String.length(name) + 6<br>    [String.pad_leading(name, padded_length, &quot;~&quot;) | prefix(others)]<br>  end<br>end</pre><pre>IO.inspect(SquidNames.prefix(SquidNames.names))<br>#=&gt;[&quot;~~~~~~sepia esculenta&quot;, &quot;~~~~~~common cuttlefish&quot;, &quot;~~~~~~sepia lycidas&quot;]</pre><p>With Elixir we tend to avoid dense code blocks that explicitly lay out how we want to do something step by step in favor of succinct, reusable functions that describes what we want done. We just say what we want and let the compiler figure out the best way to do it. Typically, we make use of recursion to do so, but I’ll get into that in greater detail later.</p><p><em>Declarative languages serve as an abstraction layer for detailing exactly how we want to obtain some result</em>. This allows the compiler to determine how to handle operations under the hood, which frequently results in more efficient code than we might write on our own imperatively.</p><h4>Core Concept 2: Functions are everything</h4><p>Functions are the basic building blocks that we use for constructing our programs. This may seem at first glance to be the same as any other paradigm, but with Functional Programming we really mean it. Everything is built with functions. With Elixir (and Functional Programming) we generally eschew control flow mechanisms like `case` and `switch` statements and `if/else` blocks, for function clauses (think “miniature” functions that handle function calls with specific sets of arguments. More on these later).</p><p>Essentially, many smaller functions are combined to build larger more complex programs.</p><p>This might seem pretty similar to a familiar Object-Oriented Programming approach in which we define methods for classes and use them as needed to operate on the data of the instance, but this is where there is a very important divergence. With Functional Programming, the data on which we are operating and the operation itself are separated. <strong>The function simply acts on data that it takes as an argument and returns a new value</strong>. That’s it.</p><p>In Object-Oriented Programming, data is often stored in objects as state, and the state (read: data) that is being operated on can impact the method itself. This is because the methods belong to that object; there is a dependency between them.</p><p>In this Ruby class, we can see how the push function belongs to the MySquids object, and its functionality is dependent on the state of the squid_names collection therein:</p><pre>class MySquids<br>  attr_reader squid_names</pre><pre>  def initialize()<br>    @squid_names = []<br>  end</pre><pre>  def push(name)<br>    # the functionality of this method depends on the state #<br>    # of the @squid_names collection #<br>    squid_names.push(name) unless names.include?(name)<br>  end</pre><pre>end</pre><pre>squids = MySquids.new<br>squids.push(&quot;inky&quot;)</pre><pre>new_squids = MySquids.new<br>new_squids.push(&quot;blinky&quot;)</pre><pre>squids.push(&quot;inky&quot;)<br># =&gt; [&quot;inky&quot;]</pre><pre>new_squids.push(&quot;inky&quot;)<br># =&gt; [&quot;blinky&quot;, &quot;inky&quot;]</pre><p>In Elixir however, we can see that while we can create a collection using a struct of the SquidNames module, the push method defined therein is not impacted by the state of the struct. It simply takes an argument (not just the struct collection) and operates independently.</p><pre>defmodule SquidNames do<br>  defstruct names: []<br>  def push(set = %{names: names}, name) do<br>    if Enum.member?(names, name) do<br>      set<br>    else<br>      %{set | names: names ++ [name]}<br>    end<br>  end<br>end</pre><pre>set = %SquidNames{}<br>set = SquidNames.push(set, &quot;inky&quot;)</pre><pre>new_set = %SquidNames{}<br>new_set = SquidNames.push(new_set, &quot;blinky&quot;)</pre><pre>IO.inspect SquidNames.push(set, &quot;inky&quot;)<br># =&gt; [&quot;inky&quot;]</pre><pre>IO.inspect SquidNames.push(new_set, &quot;inky&quot;)<br># =&gt; [&quot;blinky&quot;, &quot;inky&quot;]</pre><p>Example with ruby and elixir: ruby class with state for tracking squid names, method to add a squid only if squid name doesn’t exist (not in collection) ; elixir copy module from book with struct</p><p>Functions in Functional Programming serve a simple but critical role:</p><ol><li>Take data</li><li>Perform some operation</li><li>Return some values</li></ol><h3>Core Concept 3: Bird Immutability’s the Word</h3><p>Functional programming works with <strong>immutable</strong> values. Immutable values<em> cannot be modified</em> after their creation.</p><p>Using immutable values helps us maintain a separation between the data and data operations. When values are immutable, we know that the operation is not attached to any data other than whatever is passed in as the current argument (ideally).</p><p>Take a look at this collection in Ruby. We can push a new element into the collection, and the original object is mutated:</p><pre>squids = [&#39;inky&#39;, &#39;blinky&#39;]</pre><pre>squids.push(&#39;pinky&#39;)</pre><pre>p squids<br>#=&gt; [&#39;inky&#39;, &#39;blinky&#39;, &#39;pinky&#39;]</pre><p>On the other hand, when we push a new node into a list in Elixir, a new list is returned and the original is not mutated:</p><pre>squids = [&quot;inky&quot;, &quot;blinky&quot;]</pre><pre>squids ++ [&#39;pinky&#39;]</pre><pre>IO.inspect(squids)<br>#=&gt; [&quot;inky&quot;, &quot;blinky&quot;]<br># squids is immutable, no changes were made</pre><p>One of the main advantages that Elixir has over imperative languages, which use mutable values, is that all values in Elixir are immutable, which makes leveraging concurrency and multiple cores much easier, with less room for error/confusion.</p><p>Let’s look at a contrived example to illustrate this. Suppose we have two operations that are being performed concurrently on the same mutable data source; it is possible to introduce bugs that are very difficult to trap resulting directly from the mutability of the data.</p><pre>nums = [ 1, -3]</pre><pre># Thread 1: Take collection and find sum by popping values from collection<br># Thread 2: Take collection and reverse sign of all negative numbers</pre><pre># We would expect that if the signs of negative numbers are reversed and the sum calcullated, the sum would be 4...</pre><pre># Thread 1 -&gt; Step 1<br>sum == 0<br>nums == [ 1, -3]<br>sum += nums.pop<br>nums == [ 1 ]<br>sum == -3</pre><pre># Thread 2-&gt; Step 1<br>current_value == 1<br>current_index == 0<br>nums == [ 1, -3]<br># Positive int no need to flip</pre><pre># Thread 1 -&gt; Step 2<br>sum == -3<br>nums == [ 1 ]<br>sum += nums.pop<br>sum == -2<br>nums == []</pre><pre># Thread 2-&gt; Step 2<br>current_value == nil<br>current_index == 1<br>nums == []<br># No element at index</pre><p>Both operations point to the same data source, and because it is mutable, they act on it simultaneously, with one operation affecting the expected output of the other.</p><p>With Elixir, there is no mutability of values so operations can be performed on the same data in parallel without each affecting the outcome of the other.</p><h3>Wrapping Up</h3><p>There is a lot to learn about Elixir and Functional Programming, and we’re just getting started. Here are the key take-aways for this introduction:</p><ul><li>Elixir is a <strong>dynamically typed</strong> language</li><li>Elixir operates under the <strong>Functional Programming</strong> paradigm</li><li>Functional Programming <strong>relies on Functions instead of Objects</strong></li><li>Functional Programming makes use of <strong>Declarative Programming</strong> to abstract away imperative implementation details</li><li><strong>Functions in Elixir do three things</strong>: accept data, operate on the data, return some values</li><li><strong>Values in Elixir are <em>immutable</em></strong></li></ul><p>More exciting coverage of Elixir’s facets and fun to come!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e49b6bf6ede4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Ky’s (Somewhat Poignant) Guide to Asynchronicity and Cryptocurrencies — Part 4]]></title>
            <link>https://kaledoux.medium.com/kys-somewhat-poignant-guide-to-asynchronicity-and-cryptocurrencies-part-4-50771ae66363?source=rss-b68c7c52653b------2</link>
            <guid isPermaLink="false">https://medium.com/p/50771ae66363</guid>
            <category><![CDATA[cryptocurrency]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[async]]></category>
            <category><![CDATA[coding]]></category>
            <dc:creator><![CDATA[Kyle Ledoux]]></dc:creator>
            <pubDate>Mon, 15 Feb 2021 14:00:51 GMT</pubDate>
            <atom:updated>2021-02-15T14:07:59.602Z</atom:updated>
            <content:encoded><![CDATA[<h3><strong>Ky’s (Somewhat Poignant) Guide to Asynchronicity and Cryptocurrencies — Part 4</strong></h3><p>(Also inconsistently referred to as Ky’s Guide to Starting Over 1.8.4 or Ky’s Guide to Cryptocurrency Conclusions in future annotations and subsequent editions)</p><p><strong>One Click</strong></p><p>Every was as it should have been: the winter wind had accepted I was not partaking in its seasonal games and had shuffled off with a few strips of vinyl siding in hand, the investment banking spiders had retreated to their webs banking establishment, <em>Gotsham Regional Credit Union</em>, and I had finally put together my app to check on prices of different cryptocurrencies, CryptoChecker.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kNceQUcvuJd242679rXQYQ.jpeg" /></figure><p>I had been able to take a more comprehensive understanding of different components in JS and combine them to create an app that would let me get prices for two different currencies of interest, Bitcoin and Ethereum, plus a pricing metric on one of the rarest marbles, the Razorback Sulfite.</p><p>Knowing how async code worked was great and understanding the mechanism for making and handling requests with JS was stupendous and being able to use promises to create cleaner async code was the bee’s knees. But what did all that matter if I didn’t put it all to use, right?</p><p><strong>Good, But Still “Pyramidal” …</strong></p><p>I uploaded my app and clicked away; everything was working! Huzzah!</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcodepen.io%2Fkaledoux%2Fembed%2Fpreview%2FOJbRava%3Fheight%3D600%26slug-hash%3DOJbRava%26default-tabs%3Dcss%2Cresult%26host%3Dhttps%3A%2F%2Fcodepen.io&amp;display_name=CodePen&amp;url=https%3A%2F%2Fcodepen.io%2Fkaledoux%2Fpen%2FOJbRava&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=codepen" width="800" height="600" frameborder="0" scrolling="no"><a href="https://medium.com/media/3a68abc5ac274504f24456b501d71bc4/href">https://medium.com/media/3a68abc5ac274504f24456b501d71bc4/href</a></iframe><p>After some brief testing, I was satisfied with its functionality. I could click on one button and get three prices updated right there on the screen.</p><p>But there was something off, some piece of this that was holding a feather duster up and wandering through my synaptic hallways, tsk-tsking about “keeping up appearances.”</p><p>After some brief evaluation, I realized that there were several things I could improve through some refactoring.</p><p>I had broken pieces of the program up into separate classes to separate concerns but could do a better job of this by building out a class to handle the calls I needed to make to the API.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8a6d4123a3b48bfee838c2e5ee37a345/href">https://medium.com/media/8a6d4123a3b48bfee838c2e5ee37a345/href</a></iframe><p>By using a class like the above, I would leverage promises so that any method that needed the data could be caught in a `Promise.prototype.then` invocation. The `fetch` method is part of an extremely useful Web API; it can do many things, but at the simplest level, it can make an XHR request to a provided URL and <strong>return a promise</strong> with the results. I could use that API to keep this class very streamlined and make use of the power of promises.</p><p>I could also refactor the `UI` class to have a simpler `updatePrices` method that would take care of all updates at once. Since I wouldn’t be checking for any of the prices in isolation in this app, I might as well update them all at once, since I would be getting all their data anyways.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1c00689117b79535ae40ef7f73369f11/href">https://medium.com/media/1c00689117b79535ae40ef7f73369f11/href</a></iframe><p>The callback that would handle the update functionality when the `Update` button was clicked was lengthy; it indeed looked a bit like a pyramid… It should have been streamlined leveraging promises, and by simplifying the URL being used for the request to include both currencies. That would but a lot of extra lines out and make it much easier to read.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/150440eb0f3c037f0537804db57901e0/href">https://medium.com/media/150440eb0f3c037f0537804db57901e0/href</a></iframe><p><strong>A Bit of Elbow Grease and Beef Stew</strong></p><p>Working under the light of my many monitors, it took less time that I expected to get my updates made. I had only gotten through half a tin of stew and it was already done. Was it rudimentary? Absolutely. Was it perfect? Not by a long shot. But did it work, and do what I needed it to? Yes. Was it easier than having to negotiate a handful of sites to get the prices I wanted? Yes!</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcodepen.io%2Fkaledoux%2Fembed%2Fpreview%2FBaQLGOM%3Fheight%3D600%26slug-hash%3DBaQLGOM%26default-tabs%3Dcss%2Cresult%26host%3Dhttps%3A%2F%2Fcodepen.io&amp;display_name=CodePen&amp;url=https%3A%2F%2Fcodepen.io%2Fkaledoux%2Fpen%2FBaQLGOM&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=codepen" width="800" height="600" frameborder="0" scrolling="no"><a href="https://medium.com/media/d7f5d353e1845a6ad9f56f0f12e4b8b9/href">https://medium.com/media/d7f5d353e1845a6ad9f56f0f12e4b8b9/href</a></iframe><p>There were improvements to be made and new features to be added as the needs arose. What about all the other API interfaces that are provided? Certainly, I could find a use for some of those? I could also include a wider range of coins, or even provide some kind of selection menu to choose from a list of coins to get the prices of.</p><p>There were many improvements that could be added and perhaps some enterprising reader with an interest in the subject and a bit of fire in their belly will take this opportunity to work on the project as a means of practicing their craft. But for now, for my purposes it’s enough.</p><p>To be continued, or not… We’ll see.</p><p>Until next time, or not… We’ll see.</p><p>-Ky</p><h3>Postscript</h3><p><a href="https://kaledoux.medium.com/kys-somewhat-poignant-guide-to-asynchronicity-and-cryptocurrencies-part-1-c8cb7becedd0">The story started here</a>. Find out why I started building this app. Also, why you shouldn’t trust investment banking spiders. <strong>## link for first story ##</strong></p><p><a href="https://kaledoux.medium.com/kys-somewhat-poignant-guide-to-asynchronicity-and-cryptocurrencies-part-2-37562174b3b2">The story continued here</a>. Find out how requests can be made with JS and why pyramids are better left to the Egyptians. <strong>## link for first story ##</strong><br> <br><strong> </strong><a href="https://kaledoux.medium.com/kys-somewhat-poignant-guide-to-asynchronicity-and-cryptocurrencies-part-3-59e5303edde0">The story’s penultimate chapter</a>; promises and pickled herring.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=50771ae66363" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Ky’s (Somewhat Poignant) Guide to Asynchronicity and Cryptocurrencies — Part 3]]></title>
            <link>https://kaledoux.medium.com/kys-somewhat-poignant-guide-to-asynchronicity-and-cryptocurrencies-part-3-59e5303edde0?source=rss-b68c7c52653b------2</link>
            <guid isPermaLink="false">https://medium.com/p/59e5303edde0</guid>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[promises]]></category>
            <category><![CDATA[async]]></category>
            <dc:creator><![CDATA[Kyle Ledoux]]></dc:creator>
            <pubDate>Sun, 14 Feb 2021 22:00:43 GMT</pubDate>
            <atom:updated>2021-02-15T14:13:39.462Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>Ky’s (Somewhat Poignant) Guide to Asynchronicity and Cryptocurrencies — Part 3</strong></p><p>(Also inconsistently referred to as Ky’s Guide to Starting Over 1.8.3 or Ky’s Guide to Powerful Promises in future annotations and subsequent editions)</p><p><strong>Making a Promise You Can Keep</strong></p><p>Promises are a funny thing when you come to think on them. It’s a statement you make when you want to assure another party that you will (or won’t) do something, based on some condition or circumstance, and even if that event is in the future, you are giving your word that you will <em>eventually do something</em>.</p><p>For example, I made a promise to my Norwegian neighbor Nels (the <em>other party</em>) that if he ever brought pickled herring over to my flat (the <em>condition</em>), I would eat some (the <em>something </em>I would do). Now, in truth, I was not expecting him to swing by after returning from a visit back to Oslo with a jar of surslid, but what mattered was that I made a promise that I would do something when a condition was met, and believe me, it was met…</p><p>In JavaScript, as of ES6, JavaScript can now make promises too! But more on that in just a moment, patient readers!</p><p>This might seem like it has nothing to do with my trials and tribulations in making an app to check the prices of various cryptocurrencies but stick with me. <strong><em>Promises in JavaScript are actually quite useful</em></strong> in the context of making async calls, and I soon found that their power could be leveraged to make my code easier to write and much easier to read.</p><p><strong>Dissecting Promises</strong></p><p>It came as no surprise to me that those pesky investment bankers came scurrying back to my flat, holding out brochures about investment strategy synergy and mumbling about how the people in their webs “wanted to be there.” I had made a promise to them previously though, about what I would do if they ever came skulking around again, so I grabbed the corn husk broom from my closet and saw them off.</p><p>I made promises frequently in my everyday life, but what exactly was a Promise in JavaScript?</p><p>A promise in JS is an object that <strong>represents an eventual value</strong>; they allow us to create powerful abstractions and to provide behavior that is cumbersome to create with event listeners and traditional methods (as we will see in a moment). In effect, <em>a promise gives no guarantee of when an operation will complete</em>, but it does guarantee that <strong>when the result of the operation is available</strong> the <em>code you provide will be executed</em>, or the error handled as you specify.</p><p>It’s quite similar to any of the promises I described earlier; there is a condition that needs to be met, and an action that is executed based on the result. There was no guarantee just when the condition will be determined, but when it is, the action is taken.</p><p>This might make more sense when viewed with code, so I’ll walk you through just how I put this all together.</p><p>First I looked at how promises in JS are created, as understanding that would help me understand how they are used:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/605d8ebdba3e679aee19b0cca26bfec2/href">https://medium.com/media/605d8ebdba3e679aee19b0cca26bfec2/href</a></iframe><p>I could see that a promise <em>relies on a condition</em>. Depending on the <em>outcome of some operation</em> the condition would either be successful or unsuccessful. (This might have been receiving a response from an XHR request for example, but in this case, it was checking the value of a randomly generated number). The promise would then set its state to either ‘resolved’ or ‘rejected’, and any code chained to this promise would either enact a success callback or a failure callback based on the promise’s state and the <em>value that was returned in either case </em>(these were the arguments of the `resolve` and `reject` functions).</p><p>“But how is that useful?” you ask. Yes, promises might seem a bit ethereal now, but stick with it and the misty outline will take shape!</p><p>Contemplating the utility of promises, I considered the previous example with a randomly generated number. I could use two methods to handle the values returned by a <strong>resolved </strong>or <strong>rejected </strong>promise:</p><blockquote>- `Promise.prototype.then` —<em> invokes a callback using a </em><strong><em>resolved </em></strong><em>promise’s return</em></blockquote><blockquote>- `Promise.prototype.catch` — <em>invokes a callback using a </em><strong><em>rejected</em></strong><em> promise’s return</em></blockquote><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d9434b8c67f7a3fbd06abf6a06793b7c/href">https://medium.com/media/d9434b8c67f7a3fbd06abf6a06793b7c/href</a></iframe><p>“But, really, how is that used?” you press. Let’s give the hazy form before us some more shape…</p><p>The pivotal behavior here is that the `then` and `catch` methods <em>return promises themselves</em>, so you can chain one promise to another! <strong>This is the magic</strong> that allows us to take an elaborate configuration of nested async calls and just chain them from one promise to another!</p><p>I tried to bring this out with a more realistic example by referring back to that nasty, nested, pyramid from before. ***link here***</p><p>Here is the little Pyramid of Doom that I had constructed before as I made a few subsequent requests to get a coin id, use that id to get its price, then use the price to check the percent growth:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d08705aa47da9962e0008881e92a2358/href">https://medium.com/media/d08705aa47da9962e0008881e92a2358/href</a></iframe><p>Now, if I altered my `getCoindId` method to return a promise, instead of having to pass in the success and failure callbacks for each method, and having to nest the calls that are depending on the previous async calls all one after the other within `getCoindId` … I could do something like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a315e950ee3190eea868c4fe09699457/href">https://medium.com/media/a315e950ee3190eea868c4fe09699457/href</a></iframe><p>How much easier to read is that?</p><p>Now I would just have to handle the error cases. The good news here is that I only had to include one `catch` call at the very end, and if any of the promises in the chain were rejected, the `catch` callback would be invoked with the error passed along!</p><p>I could then simplify the calls and add an error catcher to make this code as lean and mean as possible:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/aa4d08de08d4316e6d29a54a1410d43e/href">https://medium.com/media/aa4d08de08d4316e6d29a54a1410d43e/href</a></iframe><p>Now that nebulous, amorphous cloud that was a JavaScript promise should be a fully formed turkey dinner with all the sides, and you sit with a napkin tucked into your shirt collar, utensils in either hand, ready to make a feast of this once unknowable entity.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*iIUP7K_iPH3uyJOThgdfvA.png" /></figure><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/34e9510218e7047f698ad0723400e27c/href">https://medium.com/media/34e9510218e7047f698ad0723400e27c/href</a></iframe><p>Dramatic imagery aside, I had unlocked the power of promises, and I realized that I could now leverage that power to clean up my code. Because I understood the inner workings of requests and responses in JavaScript, I could fix the errors in my CryptoChecker app and get it looking sparkly clean to boot!</p><p>Next, I would just need to put all these bits and pieces together into one cohesive bundle. Right after I cleared out the spider traps and heated up a mug of ham juice to take the chill out of the room.</p><p>To be continued, or not… We’ll see.</p><p>Until next time, or not… We’ll see.</p><p>-Ky</p><h3>Postscript</h3><p><a href="https://kaledoux.medium.com/kys-somewhat-poignant-guide-to-asynchronicity-and-cryptocurrencies-part-1-c8cb7becedd0">The story started here</a>. Find out why I started building this app. Also, why you shouldn’t trust investment banking spiders.</p><p><a href="https://kaledoux.medium.com/kys-somewhat-poignant-guide-to-asynchronicity-and-cryptocurrencies-part-2-37562174b3b2">The story continued here</a>. Find out how requests can be made with JS and why pyramids are better left to the Egyptians.<br> <br><a href="https://kaledoux.medium.com/kys-somewhat-poignant-guide-to-asynchronicity-and-cryptocurrencies-part-4-50771ae66363">The story concludes here</a>. See the CryptoChecker App in all its early 90s terminal style glory.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=59e5303edde0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Ky’s (Somewhat Poignant) Guide to Asynchronicity and Cryptocurrencies — Part 2]]></title>
            <link>https://kaledoux.medium.com/kys-somewhat-poignant-guide-to-asynchronicity-and-cryptocurrencies-part-2-37562174b3b2?source=rss-b68c7c52653b------2</link>
            <guid isPermaLink="false">https://medium.com/p/37562174b3b2</guid>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[async]]></category>
            <category><![CDATA[xhr]]></category>
            <dc:creator><![CDATA[Kyle Ledoux]]></dc:creator>
            <pubDate>Sun, 14 Feb 2021 21:59:13 GMT</pubDate>
            <atom:updated>2021-02-14T22:08:03.882Z</atom:updated>
            <content:encoded><![CDATA[<h3><strong>Ky’s (Somewhat Poignant) Guide to Asynchronicity and Cryptocurrencies — Part 2</strong></h3><p>(Also inconsistently referred to as Ky’s Guide to Starting Over 1.8.2 or Ky’s Guide to Acronyms that Start with ‘X’ in future annotations and subsequent editions)</p><p><strong>Lots and Lots of Letters</strong></p><p>The collectible marble market was on fire; prices for Symmetrical Clambroths were trouncing old English Divided Core Swirls and trading was happening at breakneck speed. On top of that, Bitcoin and Ethereum prices were fluctuating to boot. If I wanted to keep track of these prices and keep up with the rest of the cryptocurrency/marble traders, I needed to get my info faster than I was able to by clicking through different websites. Luckily, I was working on my CryptoChecker App which, when completed, would let me do just that.</p><p>A few tins of stew and a delicious, if not somewhat clumpy, glass of powdered milk had seen me through the bulk of reviewing just how async function calls could be made with JS in my browser environment. But, at that point, I was still a bit foggy on exactly how I could get information from a server using async code. I would need to create some form of request/response cycle, but I was forgetting how that was even possible.</p><p>It was time for a bit more work before I could fully flesh out the app; I needed to understand just how I could make those requests with JS, and I also needed to check the perimeter, as it seemed those investment bankers were not easily dissuaded…</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hXILb4KUGNi8HfPhhC4kgA.png" /></figure><p><strong>A Polite Request</strong></p><p>After I had finished politely requesting that the banker remove itself from my front yard and offering a mutually agreeable backup plan for the case in which they might be disinclined to acquiesce, I put my broom back in the closet and turned my attention to making a request with JavaScript.</p><p>It turns out, it wasn’t actually that hard. There is a Web API that was built for browsers to do exactly that! The hardest part of the whole endeavor is keeping all the letter straight!</p><p>`XMLHttpRequest` (also known as <strong>XHR </strong>for short) is a Web API provided by all modern browsers; it allows us to create a request object that we can use to retrieve data from a URL without having to do a full page refresh.</p><p>You might ask, “<em>What does XML stand for?</em>” <br> The short answer is, “<em>Ultimately, you don’t need to worry about it.</em>” <br> The long answer is, “<em>It stands for </em><a href="https://en.wikipedia.org/wiki/XML"><strong><em>Extensible Markup Language</em></strong></a><em>. Yes, I know extensible doesn’t start with ‘X’, that’s just how they like to make acronyms nowadays…</em>”</p><p>This API allows us to make asynchronous calls to outside resources. In my case, I wanted to grab the price of Bitcoin (among other things, but I’ll keep it simple for now); I had the API endpoint, so really, I just needed to set and send the request, then handle the response.</p><p>Using this Web API to accomplish this entailed a few different steps:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/dfe38b4e71fe4915ade593eb382ac63d/href">https://medium.com/media/dfe38b4e71fe4915ade593eb382ac63d/href</a></iframe><p>This looked to be in order, but that bundle of grey matter in my frontal cortex that nags at me to organize and optimize was shouting, “Hey, why not just grab the response body and use it directly after sending!?” This was an interesting premise; I mean, why bother with event listeners at all?</p><p>The answer become clear after I tried cutting the event listeners out of the equation altogether:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/83ae036c67bd14843e62ff788ecf06af/href">https://medium.com/media/83ae036c67bd14843e62ff788ecf06af/href</a></iframe><p>It became clear that I needed to be mindful that async calls take time! JS will evaluate the code sequentially after all, so if the value I was trying to reference relied on an XHR response that had not returned yet, that value would be undefined when JS evaluated it. The event listeners were the tool that I had to use to listen for the completion of the request, then make use of the data that I had received.</p><p>I thought of it like this: Let’s pretend I wanted to get a list of the best manuals on Ornithopter construction to read aloud. I turn to my friend Reginald and ask him to write down his top ten suggestions, but instead of waiting for him to finish writing and hand me the piece of paper back, I just snatch it back and start reading immediately. Would it be surprise to me that there was nothing written on the paper? I should think not!</p><p>I had figured out a mechanism I could use to create async request/response cycles to obtain data from a URL, and now I had remembered how to structure my event listeners with this setup so that I could actually obtain the data from the response and use it!</p><p>But the more I thought about it, the more I began to realize that this format of creating an XHR request, then relying on the listener to handle the response opened my code up to a realm of headache inducing code blocks that only fans of ancient Egyptian or perhaps Mayan architecture would enjoy…</p><p><strong>Building the Pyramids</strong></p><p>I got to thinking, “Well, I know how to make an async call to a URL and set an event listener to handle the response, when it arrives. But what happens if I need to make another sync call that depends on the response of the first? How would I set that up? What would that look like?”</p><p>In practice, I saw that this often took a common structure: a method that makes an async call takes three arguments: some value needed for the XHR call, a callback to execute <em>if the request is successful</em>, and a second callback to execute <em>if the request is not successfu</em>l.</p><p>That didn’t seem so bad, but once I considered what happened when we had to connect more than one of these methods together, a disturbing pattern emerged.</p><p>When you need to make an asynchronous call, then use the data returned from that function to make another async call, you can easily create a long chain of dependent function calls that are very difficult to decipher, also known as a “Pyramid of Doom”!</p><p>Consider the following situation: <br>I want to check the percent growth of bitcoin over the past 24 hours. But there are a few steps I will need to take first. I need to reach out to the API providing pricing data to request the coin id necessary to inquire about a specific coin. Then, with that coin id handy, I need to request the price of that coin. Once I have the pricing data in hand, I can finally request the percent growth. However, I need to account for the possibility that any of those requests might throw an error as well.</p><p>For our purpose we are going to abstract out the XHR code and keep the methods here simple, for demonstrative purposes. This might look something like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8a91215bfda67d9cbf4cf156273053ce/href">https://medium.com/media/8a91215bfda67d9cbf4cf156273053ce/href</a></iframe><p>Each method I use is going to make a request that is dependent on its first argument; it will then take a callback to execute if the request is successful, and one other callback in the case of a request failing. Having to pass all of these callbacks in for each method and having each subsequent method dependent on the value returned by the previous request means that we have to structure our code a certain way. This chain of request dependencies and callbacks starts to look an awful lot like a pyramid. A pyramid… <em>of doom</em>.</p><p>This kind of code creates serious headaches, and I quickly realized that I should avoid making code like it if I could help it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yVlSLVM1g05dbJCJ4AZrqw.png" /></figure><p>There had to be a better way out there to handle async functions such that I could make multiple requests and not have a towering pyramid of dependencies looming in my code.</p><p>As it turned out, there was such a way. It exists, I promise! The trick would be leveraging it to make my app as streamlined as I could.</p><p>To be continued, or not… We’ll see.</p><p>Until next time, or not… We’ll see.</p><p>-Ky</p><h3>Postscript</h3><p><a href="https://kaledoux.medium.com/kys-somewhat-poignant-guide-to-asynchronicity-and-cryptocurrencies-part-1-c8cb7becedd0">The story started here</a>. Find out why I started building this app. Also, why you shouldn’t trust investment banking spiders.</p><p><a href="https://kaledoux.medium.com/kys-somewhat-poignant-guide-to-asynchronicity-and-cryptocurrencies-part-3-59e5303edde0">The story continues</a>. Promises and pickled herring!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=37562174b3b2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Ky’s (Somewhat Poignant) Guide to Asynchronicity and Cryptocurrencies — Part 1]]></title>
            <link>https://medium.com/swlh/kys-somewhat-poignant-guide-to-asynchronicity-and-cryptocurrencies-part-1-c8cb7becedd0?source=rss-b68c7c52653b------2</link>
            <guid isPermaLink="false">https://medium.com/p/c8cb7becedd0</guid>
            <category><![CDATA[async]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[coding]]></category>
            <dc:creator><![CDATA[Kyle Ledoux]]></dc:creator>
            <pubDate>Sun, 14 Feb 2021 21:56:53 GMT</pubDate>
            <atom:updated>2021-02-19T18:44:23.215Z</atom:updated>
            <content:encoded><![CDATA[<h3><strong>Ky’s (Somewhat Poignant) Guide to Asynchronicity and Cryptocurrencies — Part 1</strong></h3><p>(Also inconsistently referred to as Ky’s Guide to Starting Over 1.8.1 or Ky’s Guide to Event Loops in future annotations and subsequent editions)</p><p><strong>Time for a New Hobby</strong></p><p>The wind blustered outside, throwing fistfuls of icy snowflakes at my windows and carrying off a few strips of siding when I responded by shuttering my shades and turning up the thermostat. Winter was here in all its finger numbing, nose-boogeying majesty, and this time around, I refused to play the game. I had shuttered myself in my flat, a few pallets of tinned stew to keep myself fed, and some dried fruit strips to prevent any bouts of scurvy.</p><p>I had also found a new interest that was able to scratch an itch on the hairy midback of my brain that <a href="https://medium.com/@kaledoux/kys-somewhat-poignant-guide-to-relationships-44b2af7f63d">marble collecting</a> was just not able to reach. You see, I had found out about <em>cryptocurrency </em>just<em> </em>as winter was unfurling it bivouac in the front lawn for a nice long visit. It was revelatory; a decentralized set of currencies that I could use to get my money out of the hands of those cunning, suit and necktie wearing spiders at the <em>Gotsham Regional Credit Union</em>. Instead of parking my money in the untrustworthy clutches of some cabal of investment bankers, I could take my physical currency and put it in… the blockchain… no wait, in the… cloud…?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8ccqAqPhSRJrvBq-e4ZYPQ.png" /></figure><p>Ok, truth be told, I wasn’t exactly sure how the whole thing worked, but I knew that it was <em>decentralized</em>, and that I could use it to have <em>digital currency</em>. This meant that I could unbank myself and keep my assets in cryptocurrency and another physical commodity that has always and will always command high trade-value, marbles.</p><p><strong>Data Based Decisions</strong></p><p>Once I had decided to start looking into cryptocurrencies, I realized that prices fluctuate often and sometimes wildly, so it would behoove me to track prices of my target currencies, to know when to trade one for another, or when to sell some marbles to pick up some more crypto. Who knows, if the German Symmetrical Clambroth market dips, I could always sell a bitcoin or two and clean up on the inevitable rebound!</p><p>I decided to build an interface for myself; using this interface, I could easily check the current prices of a few selected currencies and use that data to make investment and trading decisions. Data based decisions, that was the name of the game!</p><p>Sure, I could just go to some website and check the prices manually, but that’s what Joe Everyman would do; go to one website, click around a few times, get what I needed, then move to another site, repeat. No, I was going to build my own interface to get the pricing data that I wanted with the click of one button.</p><p>To do this though, I would need to leverage the power of an API, one that I could use as an interface to real-time cryptocurrency data. Luckily enough, one such API exists. <a href="https://www.coingecko.com/en">coingecko</a> provides a wide array of APIs that can be used to get all kinds of information about all kinds of cryptocurrencies, and it is free to use!</p><p>With the API picked out, I read through the documentation and tried plugging my code in. I quickly realized from the slew of errors that were thrown, that I was doing something wrong. It appeared that I did not take a few things into account. The first and most major was this: an API call to an outside data source needed to function as an asynchronous operation, and I hadn’t accounted for this in my code, having framed everything in the perspective of sequential, near-instantaneous evaluation. The second was that I had underestimated the vengeful nature of those bankers at Gotsham, and needed to spider proof my flat.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*Obv4Fr6CnF7rO4PhOBuM_A.png" /></figure><p><strong>Thinking Out of Sequence</strong></p><p>Asynchronous code was something I had not accounted for, much to my embarrassment. But to be fair, JavaScript can be kind of complicated with how some operations are resolved. It ultimately comes down to whether the code is <em>synchronous </em>or <em>asynchronous</em>. I realized that I had not been considering the elements of JS that surrounded these kinds of operations, and why that would cause issues with a basic request to an API. It would be important to understand these pieces, as they would ultimately inform what I could do with my code in this circumstance and how I might do it!</p><p>To start with, I had to remember that JS is evaluated sequentially; I mentioned this previously, but what did that actually mean? It meant that code in any JavaScript file is read line by line, in sequential order. Consider the following code:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bb9868e3021864a4d4c61df1269a57aa/href">https://medium.com/media/bb9868e3021864a4d4c61df1269a57aa/href</a></iframe><p>Each line is read in order from top to bottom and each line is executed in that order. Sure, if there is a closure or variable referenced down the line, JS might hop back up to its location to complete execution, but it does not deviate from the order in which it reads the file: top to bottom, one line at a time, in order.</p><p>This sequential processing is important when I also considered that JS is a single-threaded language, it can <em>only run one operation at a time</em>, ever. But what did that mean when it came to building out an app that could get pricing data from the chosen API? Well, consider this little conundrum:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/477ad8a824c23cd27101cac189f5eee3/href">https://medium.com/media/477ad8a824c23cd27101cac189f5eee3/href</a></iframe><p>If JS runs sequentially, and it can only do one thing at a time, then when it encounters a line of code that might take a few seconds to execute, the entire program comes to a standstill while that is happening. This execution bottle-necking can have huge impacts on the performance of the program, and its usability.</p><p>Luckily for us though, there are folks who were savvy enough to realize what a huge problem this might be. After all, how could one expect an avid marble collector to sit for several seconds while their <em>marblemaniacs.net</em> homepage loaded in small chunks as several small API calls were made to various marble collecting databases? <em>It would be an untenable, uninspiring experience</em>.</p><p>This is why there are components that function with the JS runtime which allow us to perform some operations synchronously and others asynchronously. Synchronous operations run following the sequential order of execution, while asynchronous operations run by starting execution when they are encountered, then completing their execution after some period of time has elapsed. Typically, this elapsed time is the time it takes to make some kind of request and receive a response, but we can also use a useful method to demonstrate how asynchronous code works without having to worry about all that just yet.</p><blockquote><strong>Side Note</strong>: The mechanism for asynchronous callbacks for JS is not actually provided by the runtime, it is a sequentially executed runtime after all. Rather, the browser in which JS is being executed will provide the Web APIs to make concurrent operation possible (or C++ APIs for Node).</blockquote><p><strong>Timeout</strong></p><p>While working on my price checking application and stumbling through issues with mishandling asynchronous code, I thought it would be best to go back and reexamine just <em>how async code was processed</em>. After all, rushing only led to products of poor quality, right?</p><p>The method I could use to help visualize async code was `setTimeout`. It is a Web API provided by browsers (<em>refer to the previous note on browser APIs versus JS runtime native features</em>), and I wanted to use the browser as my framework, as I would be using browser-based JS for my app.</p><p>`setTimeout` is simple enough to understand; it takes two arguments, a <em>callback </em>and a <strong>number</strong>. The <em>callback </em>is executed after the <strong>number </strong>of milliseconds has elapsed.</p><p>Check out this example:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e8e52ee40d2e2b00e73076b27a523847/href">https://medium.com/media/e8e52ee40d2e2b00e73076b27a523847/href</a></iframe><p>We can see here that even though the `setTimeout` invocation and its callback are encountered second in this block of code, the callback is not executed until well after the last line of code was executed and ‘Position: 3 — Executed: Second’ was logged to the screen.</p><p>This makes it obvious that the invocation of `setTimeout` is being handled differently; after all, JS is single-threaded and sequential, so if it weren’t being handled differently, the program would bottleneck until the delay was resolved. But it doesn’t! The program execution continues to flow and the next line is executed as the delay for `setTimeout` is being resolved!</p><p><strong>That is the beauty of async code</strong>; <em>we can let the async function do what it needs to, and once it is ready to resume, it is joined back into the normal flow of execution</em>.</p><p>We can see how JS handles multiple async calls that might occur in the same program:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7459220ec55c5d58ef19f4fe746251af/href">https://medium.com/media/7459220ec55c5d58ef19f4fe746251af/href</a></iframe><p>There is more than one async call (to `setTimeout`) and one takes longer to resolve than the other, but there are no bottlenecks and no errors. The async functions are handled and their callbacks executed once their delays have elapsed.</p><p>This was all well and good, but it seemed to open the door for another major question in understanding async code. <em>How does the browser create an environment that allows for concurrent execution when JS is a single-threaded runtime?</em></p><p><strong>Stacks, Loops, and Queues</strong></p><p>My shade flitted ever so slightly, as if pushed by the gentlest of breaths, signaling that despite my best efforts, winter would find a way to make itself known, even if I had closed myself inside, curled under my warmest jumper. I was eating a bowl of Loops and Queues, (quite popular over here, I assure you) and thinking about just how browsers handle the processing of async functions that are encountered in the JS runtime. Clearly, they could handle code that took extra time to execute without totally bottlenecking all other operations, but what was the mechanism that allowed that to happen, you might ask?</p><p>This is where the cooperation of a few separate piece come into play. The JS runtime’s Call Stack and the browser’s Web APIs, Event Loop, and Message Queue all work together to create an environment that allows for some degree of concurrent execution despite the single threaded nature of the JS runtime.</p><p>Prepare yourself, as this might seem a bit dense. Don’t fret though, visual accompaniment to follow: <br> The JS runtime passes stack frames to the Call Stack where they are executed in the order that they are encountered. It operates on a last in, first out basis, so the most recent call goes on the top of the stack and must be executed before any calls further down on the stack are executed. I equate this to my reading list and the pile of old books on my desk; I can easily add another book on my “need to read” list and toss that book on the top of the pile, but that means that I now have to take that book off the top of the pile and read it first before I get to any of the others (or the rest of the pile will fall apart and my list will become an incomprehensible tangle of dusty pages).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jODG06nn0kYqBGjMcf8jpw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0Vm_IKrUTSeAgQncPwZq7g.jpeg" /></figure><p>We can show how this process works with an extremely simplified model of the Call Stack:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/792/1*KK7RKsvCqdCtXYJyWvEeEA.gif" /></figure><p>Based on this example we can see that the method invocations that are encountered must be pushed to the stack in the order they are read and executed, then popped from the stack as they are resolved. This fits with what we have already learned about the JS runtime’s handling of function invocations. But, what did this model mean for an async call? If it runs asynchronously, then it can’t possibly sit on the call stack, that would cause a bottleneck.</p><p>It doesn’t! An async call is handled by a browser Web API that pulls the callback from the call stack, runs the async operation, then passes the callback over to the Message Queue. But how does the callback ever get executed if it gets pulled from the call stack, and passed over to the Message Queue? That’s where the Event Loop comes into play. The Event Loop is a mechanism that acts as a go-between for the Message Queue and the Call Stack; its job is to monitor the Call Stack to see when the Call Stack is empty. When the Event Loop sees that the Call Stack is empty, it will check the Message Queue for any callbacks that are ready to be evaluated. If there is a callback waiting, the Event Loop will then pass the callback over to the Call Stack to be executed.</p><p>I fumbled through my notes and tried to remember how this all worked. An empty tin of stew clattered to the ground as I knocked it over, along with a leaning pile of books. It’s one thing to talk about this complex chain of browser mechanisms and runtimes, but having a solid mental model was an entirely different thing, kind of like <em>saying </em>you’ll eat pickled herring is one thing, but when your neighbor comes back from Oslo with a jarful of the stuff…</p><p>Luckily, I did find a powerful tool for visualizing these relationships among my scattered notes. <a href="http://latentflip.com/loupe/">Loupe</a> is a free tool that can visualize exactly what is happening at each stage of an async call. I plugged away some code in Loupe and solidified my understanding of the Call Stack, Web API, Message Queue and Event Loop. And with that… I felt ready to begin addressing some issues in my application.</p><p><strong>An Inconclusive Conclusion</strong></p><p>A greasy droplet of stew gravy dribbled down my chin and splotched into a nice new stain my pair of well-worn slacks. I didn’t care; at that point I was on the verge of getting my cryptocurrency application all figured out. Now that I knew what asynchronous calls were and how browsers and the JS runtime interacted to make such concurrent operations possible, I felt like I was ready to figure out exactly how to get my application working.</p><p>Sliding the finished tin over amid a growing pile of its compatriots, I pulled up a few different websites, cryptoChecker.com, marblemaniacs.net, and a few others; I sorted through them and noted the prices of the cryptocurrencies that interested me, like Bitcoin and Ethereum, and checked the prices of a few highly prized marble varieties. Unfortunately, I had to do this the hard way, the manual way. But not for long. Soon, I would have my CryptoChecker app functional, and I could get all of this done with one click.</p><p>However, there was another piece that I needed to work out before I could make that happen…</p><p>To be continued, or not… We’ll see.</p><p>Until next time, or not… We’ll see.</p><p>-Ky</p><h3>Postscript</h3><p><a href="https://kaledoux.medium.com/kys-somewhat-poignant-guide-to-asynchronicity-and-cryptocurrencies-part-2-37562174b3b2">The story continues</a>. Find out how XHR is used to get the prices Ky is looking for.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c8cb7becedd0" width="1" height="1" alt=""><hr><p><a href="https://medium.com/swlh/kys-somewhat-poignant-guide-to-asynchronicity-and-cryptocurrencies-part-1-c8cb7becedd0">Ky’s (Somewhat Poignant) Guide to Asynchronicity and Cryptocurrencies — Part 1</a> was originally published in <a href="https://medium.com/swlh">The Startup</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>