<?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 Ian Grubb on Medium]]></title>
        <description><![CDATA[Stories by Ian Grubb on Medium]]></description>
        <link>https://medium.com/@ian_grubb?source=rss-47e6201de8e0------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/2*dh1szNh9SoAdhVnr6YNMLQ.jpeg</url>
            <title>Stories by Ian Grubb on Medium</title>
            <link>https://medium.com/@ian_grubb?source=rss-47e6201de8e0------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 05 Dec 2026 08:09:53 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@ian_grubb/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[How to Manage Scope While Chaining Array Methods]]></title>
            <link>https://javascript.plainenglish.io/how-to-manage-scope-while-chaining-array-methods-3ccbd54d00e8?source=rss-47e6201de8e0------2</link>
            <guid isPermaLink="false">https://medium.com/p/3ccbd54d00e8</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[javascript-tips]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[functional-programming]]></category>
            <category><![CDATA[web-development]]></category>
            <dc:creator><![CDATA[Ian Grubb]]></dc:creator>
            <pubDate>Wed, 13 Jan 2021 19:48:46 GMT</pubDate>
            <atom:updated>2021-01-14T22:26:45.376Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*dIM1OZqxtHqdC80s" /><figcaption>Photo by <a href="https://unsplash.com/@daniel_von_appen?utm_source=medium&amp;utm_medium=referral">Daniel von Appen</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Functional programming is a deep topic that has foundations in some pretty complicated mathematics. Luckily, you don’t have to understand all that to benefit from using functional techniques in your code. You probably use some already — array methods like map and filter have their origins in functional programming, but they’re implemented in many non-functional languages as well.</p><p>That being said, learning more about functional programming can help you make the most of these features. I recently worked through a helpful <a href="http://reactivex.io/learnrx/">guide</a> to functional programming in JS, which I highly recommend. It goes over a lot more than I can talk about here, but I want to share one of the techniques I took from it. It’s ultimately a pretty straightforward technique, but it can be really useful and is illustrative of some deeper concepts in functional programming.</p><p>First, let’s talk about the problem it helps solve. Imagine you’re performing some data transformations on an array by chaining together map and filter methods. To have a simple (if a bit arbitrary) example, let’s say you’re given an array of numbers and you have to (1) double them, (2) remove any of the resulting numbers that are greater than three, and (3) reduce any remaining numbers by five. You could do that with map and filter as follows:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e65098b384890244860f51f350eaeff7/href">https://medium.com/media/e65098b384890244860f51f350eaeff7/href</a></iframe><p>Nothing too tricky so far, but now you get a further requirement: take the resulting numbers and, for each one, return the difference between it and the original number it corresponds to in the input array. For instance, since 2 gets mapped to 4, preserved through the filter, and then mapped to -1, we should return an array that contains -3 (i.e. -1 minus 2).</p><p>The issue here is knowing which numbers correspond to each other. By the time you get to the end of the chain, the original numbers are out of scope. What we need is some way to keep track of what each number in the chain originated from so that we can eventually perform the required calculation.</p><p>There’s a kind of brute force solution here: just pass the original value as an argument to each of the callbacks in the chain, giving you access to the value when you need it:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b0d7dd29ddbaa8e247cbf70c981dea00/href">https://medium.com/media/b0d7dd29ddbaa8e247cbf70c981dea00/href</a></iframe><p>I used pattern matching to try to make this as elegant as possible, but it’s still pretty ugly code. Good functions should have a single responsibility, but these have two: performing a calculation and preserving data.</p><p>Let’s see how to do better. The key here is the <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/flatMap">flatMap</a> method, which is a relatively recent addition to JavaScript. The flatMap method is just a way to conveniently map over an array and then flatten the resulting array. It expects a callback that returns an array. It applies the callback to every element of the initial array and collects all the elements from all the returned arrays, returning them in a single array.</p><p>That’s a bit complicated in the abstract, so let’s look at an example. Here’s how you could take an array of numbers and get an array of all the square roots of those numbers:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/34fa6a1353cfd2c1580c844ca1ccd371/href">https://medium.com/media/34fa6a1353cfd2c1580c844ca1ccd371/href</a></iframe><p>The callback function takes a number (e.g. 4) and returns an array of that number’s positive and negative roots (e.g. [2, -2]). Because flatMap flattens, we end up with all of those pairs of roots in a single array.</p><p>Alright, we’re ready for the cleaner solution to our earlier problem. Whenever you have an array of values you want to save for a later calculation, here’s what you can do: (1) flatMap over those values, (2) for each value, map it onto a singleton array containing just that value (e.g. 1 gets mapped to [1]), and (3) perform exactly the same maps and filters as before on this array. When you do so, you’ll have the original value in scope, ready to be used whenever you like:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e6291a9c55c60002873709724a14781c/href">https://medium.com/media/e6291a9c55c60002873709724a14781c/href</a></iframe><p>If you compare this with the initial code, you’ll see that that lines 7–9 are exactly the same as lines 5–7 from before. But because all of these maps and filters now happen within the scope of the flatMap’s callback function, the original value is always available — that’s how we can refer to it at line 10, without having to thread it through each of the other callback functions.</p><p>It might not be immediately obvious that this gives the right result, but surprisingly it does work. I encourage you to draw out the data transformations to prove to this to yourself — that’s the only way I was able to fully digest what’s going on.</p><p>Admittedly, there’s something a bit weird about the technique. It’s surprising that we’re using 2D arrays in a context where they’re not technically necessary. But that’s part of why the technique is so interesting: it shows that sometimes the easiest way to process a 1D array of data is to turn it into a 2D array, perform operations on that array, and then flatten it back out into a 1D array. Knowing that that’s a possibility gives you a powerful tool for writing functional code that transforms arrays of data.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3ccbd54d00e8" width="1" height="1" alt=""><hr><p><a href="https://javascript.plainenglish.io/how-to-manage-scope-while-chaining-array-methods-3ccbd54d00e8">How to Manage Scope While Chaining Array Methods</a> was originally published in <a href="https://javascript.plainenglish.io/">JavaScript in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Data Structures and Immutability]]></title>
            <link>https://medium.com/@ian_grubb/data-structures-and-immutability-e510dead19db?source=rss-47e6201de8e0------2</link>
            <guid isPermaLink="false">https://medium.com/p/e510dead19db</guid>
            <category><![CDATA[immutability]]></category>
            <category><![CDATA[elixir]]></category>
            <category><![CDATA[algorithms]]></category>
            <category><![CDATA[functional-programming]]></category>
            <category><![CDATA[data-structures]]></category>
            <dc:creator><![CDATA[Ian Grubb]]></dc:creator>
            <pubDate>Wed, 30 Dec 2020 19:11:48 GMT</pubDate>
            <atom:updated>2020-12-30T19:11:48.465Z</atom:updated>
            <content:encoded><![CDATA[<p>This December I’ve been working though the latest iteration of <a href="https://adventofcode.com/2020/">Advent of Code</a>. In case you haven’t seen it before, it consists of one holiday-themed coding challenge per day until Christmas. I decided I’d work through these challenges using Elixir, in order to help reinforce my understanding of the language.</p><p>Elixir is a functional language that doesn’t allow mutable data. Once defined, a piece of data stays the same way until it’s discarded. If an application needs to change state, you have to create a brand new piece of data to use in place of the old state, rather than simply mutating the old state in place. There are advantages to this approach, especially when it comes to handling concurrent processes (one of Elixir’s big strengths).</p><p>Unfortunately, immutable data has costs as well. Many of the standard approaches to algorithm problems rely on mutation in order to maximize efficiency. Taking the standard implementation of an algorithm and patching it so it works with immutable data often has inadequate results. That’s not to say that you can’t write efficient algorithms in functional languages, but doing so often require some creativity.</p><p>In order to get better at writing algorithms in Elixir, I’ve had to unlearn some of my usual assumptions and learn new techniques for working with immutable data. This was initially frustrating, but I soon began to enjoy the special challenges involved in writing algorithms for immutable data. Let me share some of the important points I’ve learned so far.</p><h3>Linked Lists vs Arrays</h3><p>In most programming languages, arrays are the default way to store sequential data. Linked lists are an alternative, but they aren’t used as frequently. However, linked lists have significant advantages over arrays if you’re not allowed to mutate your data. For this reason, Elixir uses linked lists for its default list implementation.</p><p>To understand why, think about what’s involved in inserting a new element into an immutable list. Because of immutability, you can’t just change the old list so that it has the new element. Instead, what you do is take the old list and the new element, and you use them to return a new list containing the new element and all of the elements in the old list.</p><p>If you implement an immutable list using an array, the length of these insertions take grows linearly with the size of the array. Every insertion requires copying the old array in its entirety, which means copying every one of its elements. Given how often insertions are performed on lists, we’d like to avoid this if at all possible.</p><p>We can do better with linked lists, since inserting at the start of a linked list takes constant time. Any linked list is really just a node containing a value and a pointer to another linked list. To insert a new element into a linked list, all we have to do is create the new node, give it the new value, and point it to the old list. That gives us constant time insertions that don’t require mutation.</p><h3>Queues</h3><p>Linked lists have constant time addition and removal from the front of the list, so it’s really straightforward to use one to implement a stack. Implementing queues with linked lists is tricker, since adding or removing from the end of a linked list takes linear time. If you use a linked list to implement a queue, you’ll inevitably end up performing too many linear time operations, resulting in an inefficient data structure.</p><p>An efficient, immutable queue is possible, it’s just not quite as straightforward. The basic strategy is to represent the queue with two linked lists, one containing the front portion of the queue and the other containing the back portion of the queue. You add an element to the queue by adding it as the first element of the back list and you remove an element from the queue by removing the first element of the front list. The only catch is that sometimes you’ll run out of elements on the front list to remove, and in that case you reverse the back list and use it as the new front list.</p><p>Here’s a simple implementation of this idea in Elixir. Besides additions and removals, this queue supports the ability to peak at the first element. To make peaking constant time, I had to add some conditions to ensure that if there are any elements in the queue, there’s at least one element in the front list.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9042a9d28be232982f003ea48f5318a9/href">https://medium.com/media/9042a9d28be232982f003ea48f5318a9/href</a></iframe><p>While peaking and adding both have constant time complexity, things are a little more complicated with removing. Whenever there’s more than one element in the front list, removing the first element takes constant time. But if there’s only one element in the front list, we have to spend linear time reversing the back list. Fortunately, this type of removal is guaranteed to happen either infrequently or when there aren’t many elements in the back list to reverse, meaning that the amortized time complexity for removals is constant.</p><h3>Zippers</h3><p>Linked lists are convenient when all you have to do is traverse over some elements and do something for each of them. But sometimes list traversal can get more complicated — you might have to consider what’s adjacent to the current value in the list, and you might have to traverse backwards or forwards at different points in the list. This is easy enough to do with arrays, but not with linked lists.</p><p>Fortunately, there’s a solution: implement a zipper. Zippers are data structures that wrap other data structures, allowing us to explicitly represent a stage in the traversal of the underlying data structure. You can make zippers for many kinds of data structures, but we’ll just look at list zippers. A zipped list might represent the previous elements that have already been traversed, the current element, and remaining elements left to traverse. If a list were a book, a zipped list would be a book with a bookmark in it: it has all the data contained in the list, plus additional data that represents a position within that list.</p><p>Here’s a simple ListZipper implementation, which gives us the ability to create zipped lists out of lists, move forward and backward in the list, and observe the current element.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c053696c7ef4e07e60ec798b3650b86b/href">https://medium.com/media/c053696c7ef4e07e60ec798b3650b86b/href</a></iframe><p>The convenience of this implementation doesn’t come with a significant cost in terms of speed. Creating the zipped list just requires pointing to the existing list, so that takes constant time. Moving forward and backward just requires moving a single element from the front of one linked list to the front of another, so these actions take constant time as well.</p><h3>Hash Maps</h3><p>Like other languages, Elixir provides a way to store key-value data in a hash map. However, the implementation of hash maps in Elixir is a bit different than normal, which gives it different performance characteristics.</p><p>In most languages, the basic strategy for building a hash map involves combining an array with a hashing function. The hashing function maps keys to array indices and values are stored in the array at the appropriate indices. Given a sensible strategy for avoiding collisions, this gives us a data structure with constant time value lookup.</p><p>How do we build hash maps without using arrays? We could just implement the previous strategy and use linked lists in place of arrays, but that would result in a hash map with linear time value lookups. Given that the usefulness of hash maps often consists in their fast value lookups, that wouldn’t be an acceptable solution.</p><p>Fortunately, there are other ways to implement hash maps. In Elixir, this is done with a hash tree structure. I haven’t looked into the details of this implementation, but the important upshot is that Elixir maps have logarithmic time complexity for value lookups. That’s not quite as good as constant time lookup, but good enough that Elixir maps are still a valuable tool for writing efficient algorithms.</p><p>Because of their logarithmic lookup times, maps can be used as a reasonable replacement for arrays in certain cases. For problems where accessing sequential data by index is a necessity, one approach is to just use a map with numbers for keys. That doesn’t give you quite the same speed you’d get using an array, since arrays have constant lookup time, rather than logarithmic. But, logarithmic time complexity is still fast enough in many cases, and you’ll certainly get a better result than using a linked list.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e510dead19db" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Modeling Bowling in Elixir]]></title>
            <link>https://medium.com/@ian_grubb/modeling-bowling-in-elixir-d7bed1833b9?source=rss-47e6201de8e0------2</link>
            <guid isPermaLink="false">https://medium.com/p/d7bed1833b9</guid>
            <category><![CDATA[functional-programming]]></category>
            <category><![CDATA[elixir]]></category>
            <category><![CDATA[pipes]]></category>
            <category><![CDATA[pattern-matching]]></category>
            <dc:creator><![CDATA[Ian Grubb]]></dc:creator>
            <pubDate>Mon, 02 Nov 2020 18:51:22 GMT</pubDate>
            <atom:updated>2020-11-02T18:51:22.077Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*5fsLH2nsO4SRO6so" /><figcaption>Photo by <a href="https://unsplash.com/@michellem18?utm_source=medium&amp;utm_medium=referral">Michelle McEwen</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>The rules of bowling seem simple: there are 10 frames per game, each frame has 10 pins, and for each frame you get two chances to knock down those pins. But there are a lot of weird conditions and edge cases. You get points for the pins you knock down, but also bonus points based on previous strikes and spares. Frames have two rolls each, except when you get a strike and immediately move to the next frame after the first roll. A game lasts for ten frames, but there can also be bonus throws at the end of the game to account for a spare on the last frame or a strike on the last two frames.</p><p>I’ve been thinking about this because I recently completed an <a href="https://exercism.io/">Exercism</a> challenge that involved using Elixir to model games of bowling and compute scores at the end of each game. Elixir is a functional programming language. It’s built on Erlang, making it an excellent tool for concurrent programming. It’s also inspired by Ruby, which you can see in Elixir’s syntax and its concern for developer experience.</p><p>Elixir has a lot of great features that I can’t get into here, but some of my favorites are simple tools that help me write cleaner code and manage complex conditions. These were really useful for the Bowling exercise, so I figured I would walk through my solution and show off what Elixir can do. Don’t worry if you haven’t used Elixir before, I’ll be explaining everything along the way!</p><h3>Code Organization in Elixir</h3><p>Elixir programs are built from functions that are organized into modules. Within a module, you can call a function just using its name. Outside of the module, you call the function by prepending the module name and a period.</p><p>Solving the bowling exercise requires writing a Bowling module that has three public functions: one that returns a newly started bowling game, one that returns a bowling game after some role has occurred, and one that returns the score of a bowling game. Here’s an outline:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/15149b24552c6786740d98d677359d2a/href">https://medium.com/media/15149b24552c6786740d98d677359d2a/href</a></iframe><p>We’ll need to fill in the logic for each of the functions, and along the way we’ll make some private functions (usable only within the module) to help keep the code clean.</p><p>In a way, modules are like the classes of object oriented languages, since modules are how Elixir encourages separation of concerns. However, Elixir doesn’t have classes or objects. Data structures can be used to represent things in the world, but they don’t work the same as objects — you can’t call methods on them and you can’t mutate their state.</p><h3>Maps and Tuples</h3><p>We need a data structure that represents all the relevant facts about a bowling game. There are different ways of going here, but I think it’s most convenient to break a bowling game down into a few different parts. First, there’s the phase of the game: the current frame and the current attempt within that frame. Second, there’s the number of pins currently standing. Third, there’s current total score. And forth, there’s some kind of record about past strikes and spare, so that we know how to score future rolls.</p><p>That clearly calls for some kind of key-value store. In Elixir, that’s a map. Here’s the function we need to return the initial state of a game:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1d0bb1afcea47a5aa2c2f589a3cdfe13/href">https://medium.com/media/1d0bb1afcea47a5aa2c2f589a3cdfe13/href</a></iframe><p>As you can see, maps in Elixir can be written out within a set of curly braces, prefixed by a percent sign. This map has keys for frame, attempt, pins, score, and multipliers. Elixir functions implicitly return their last expression, so it’s enough to simply write out the map we want returned.</p><p>Maybe you noticed that the multipliers key has some data in curly braces, but without a percentage sign. That’s actually tuple, not a map. Tuples are fixed-length containers that are frequently used for pattern matching (we’ll see how in a moment). Here, I’m using the tuple to represent the bonuses that the next two rolls get, based on previous strikes and spares. The default multiplier is 1, meaning that no bonus gets applied.</p><h3>Control Flow with Case and Cond</h3><p>Now that we have a function that returns an initial game state, let’s work on calculating the updated game after a roll. In a functional language like Elixir, clean code consists of small, composable functions. Since the roll function should first validate the input and then return an updated game if the input is valid, my plan is to write a function for each of those behaviors. All I want to do in the. roll function itself is compose these two helper functions.</p><p>After calling the roll validation function, we should do one of two things. If the roll is valid, the validation function should indicate that we should return an updated game. If the roll is invalid, the validation should return an error with information about what’s wrong, so that this error can be returned by the roll function. The best way to do this is with Elixir’s case clause:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/63b341d3efc100334e34255fabfb09ef/href">https://medium.com/media/63b341d3efc100334e34255fabfb09ef/href</a></iframe><p>Here’s how this works. First, the return value validate_roll gets computed. Then, that value gets compared with the expressions in the do/end block. Elixir looks for the first match it can find between the return value and an expression on the left side of an arrow. Once it finds a match, it returns the value on the right side of that arrow.</p><p>In the roll function, there are two possible expressions to match: the atom :ok and the variable error. The only value that matches :ok is :ok, so that’s what the validate_roll function should return to indicate the validity of the roll. Any other value matches the variable error, thereby assigning a value to that variable. That’s how we can return that value on the right side of the arrow, passing the error message along as the return value for roll.</p><p>Let me pause to emphasize what’s happening here, since it’s not possible in many programming languages: Elixir’s case statements allow you to simultaneously handle control flow and perform variable assignments. This is an incredibly convenient feature that allows for concise and expressive code.</p><p>The validate_roll function should check for a three error conditions: when the roll is greater than the number of pins, when the roll is negative, and when the roll occurs after the game is over. It should return an error message if one of those conditions is met, and an :ok atom otherwise. We can do this another kind of control flow syntax, the cond clause:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b2a139210d465f25b50a0551902f3c4a/href">https://medium.com/media/b2a139210d465f25b50a0551902f3c4a/href</a></iframe><p>Inside of the do/end block, Elixir checks for the first expression on the left side of an arrow that returns true and returns the value on the right side of that arrow. The true on the left side of the last arrow acts as an else-clause, which runs in case none of the other conditions are true.</p><p>I extracted the logic to check whether a game is complete into its own helper function. Once a game’s tenth frame is complete, we’ll set its frame to nil. To check whether a game is complete, we check that it’s past its tenth frame and that there are no extra rolls to process.</p><p>Extracting this logic as a helper function allows it to be reused elsewhere. The exercise requires the score function only returns a score value for a game that’s complete. Now that we have a function that checks for game completeness, we can go ahead and write score:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/23a29f15cabd645f5a23b25553775e04/href">https://medium.com/media/23a29f15cabd645f5a23b25553775e04/href</a></iframe><h3>Data Pipelines</h3><p>Now that we’ve handled input validation, it’s time to write the code that updates a game given a valid roll. Updating a game is a complex process, so it helps to break the update down into a sequence of data transformations. Here’s the breakdown that makes sense to me: (1) process the roll by adding to the score and reducing the pin count, (2) update the multiplier for future roles, (3) update the current frame and attempt, and (4) reset the pins to ten if necessary.</p><p>For each of these transformations, we’ll write a function that takes a game as its first argument and returns an updated game. We’ll put these functions together in the update_game function using the pipe operator (|&gt;). The pipe lets us take the return value of a function and pass it in as the first argument to another function. In Elixir, it’s common to chain these together to build data transformation pipelines. Here’s what this looks like in our case:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/78c5e65cc14c387bf671c37d86da478f/href">https://medium.com/media/78c5e65cc14c387bf671c37d86da478f/href</a></iframe><p>We feed the initial game into the pipeline and it gets piped through each transformation function in succession. Note that (despite appearances) each of these functions accepts a game as its first argument. In each case the game gets past in implicitly by the pipe operator. The explicit arguments like roll and game.frame provide auxiliary information needed to update the game.</p><h3>Pattern Matching</h3><p>All that’s left now is to write the four data transformation functions needed for the pipeline. These functions will use Elixir’s pattern matching capabilities to define variables and handle control flow. The easiest way to understand how this works is to see it in practice.</p><p>Each of the functions accepts a map that represents a game’s state, and these functions will each need to access some of the keys in this map. One way to do this is by pattern matching within function signatures. Here’s how this works for process_roll:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e88b344364f6edb2e3866e4c5406522a/href">https://medium.com/media/e88b344364f6edb2e3866e4c5406522a/href</a></iframe><p>The function accepts two arguments and those get put into the variables game and roll. In addition, the game is a map with the keys pins, score, multipliers, and frame, letting us to define variables based on the values for those keys. We can even match on the tuple in multipliers and just pull out the first multiplier, which is the one relevant to calculating the score for the current roll. We use an underscore in place of the second multiplier to indicate that some value is in that position, but that it isn’t relevant to the present function.</p><p>The adjusted multiplier is there to handle bonus rolls at the end of the game. In order to make these rolls count for the correct amount, we have to reduce the multiplier by one when we use it to determine what score to add for the bonus rolls.</p><p>The function returns an updated game state. The %{map| key: value} syntax is just a way to return a copy of map where certain keys have their values replaced in the specified way. In this case, we return a copy of the original game state, except we update the total score and the number of standing pins.</p><p>The other three functions all follow this pattern of extracting old parts of game state through pattern matching and then returning a copy of that game state with updates. Here’s update_multipliers, which updates the multipliers and accounts for strikes and spares:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f4c7f1bf6e3799ecf9162d22bb449faf/href">https://medium.com/media/f4c7f1bf6e3799ecf9162d22bb449faf/href</a></iframe><p>We’re using a case clause again, except this time there’s more structure to match on. A strike happens when there are no pins after one attempt at the frame. A spare happens when there are no pins after two attempts at the frame. We check for these conditions by building a tuple with the pin and attempt counts and then pattern matching on the relevant combinations.</p><p>We can take a similar approach to the logic for update_turn, which needs to update a game based on its current attempt, frame, and pin count:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bed7ccba5dcfaaba452a9647e4c1111b/href">https://medium.com/media/bed7ccba5dcfaaba452a9647e4c1111b/href</a></iframe><p>Since the same updates can happen under different conditions, I’ve extracted them out into helper functions. The game’s turn info stays the same if it’s already in extra rolls. The game goes into extra rolls after the second attempt on the tenth frame or after a strike on the tenth frame. The game goes into a new frame in any other case where there’s a second attempt or a strike. And whenever there’s a single attempt without a strike, the game goes on to the second attempt for the same frame.</p><p>At the end of the pipeline, we call maybe_reset_pins to reset the pins if there are no current pins or if there’s a new frame. We can handle this update with another cond clause:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0298eac50fca4b4b3ee3cb3f502181fa/href">https://medium.com/media/0298eac50fca4b4b3ee3cb3f502181fa/href</a></iframe><h3>Conclusion</h3><p>Taken together, the functions above successfully manage the state changes for any game of bowling. By giving us tools like case statements, pipes, and pattern matching, Elixir helps us to manage the complexities in this domain in an elegant way. Elixir has a lot more to offer when it comes to performance, concurrency, and developer tooling, but it’s hard to overstate the benefits that Elixir’s various coding idioms have on day-to-day developer experience. I’d definitely encourage taking a closer look if you’re thinking about picking up a new programming language.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d7bed1833b9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Solve First Missing Positive]]></title>
            <link>https://medium.com/swlh/how-to-solve-first-missing-positive-90e6ed29ca81?source=rss-47e6201de8e0------2</link>
            <guid isPermaLink="false">https://medium.com/p/90e6ed29ca81</guid>
            <category><![CDATA[leetcode]]></category>
            <category><![CDATA[algorithms]]></category>
            <dc:creator><![CDATA[Ian Grubb]]></dc:creator>
            <pubDate>Mon, 19 Oct 2020 13:13:25 GMT</pubDate>
            <atom:updated>2020-10-22T21:39:53.326Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*s60AhJVUFE3A4-MP" /><figcaption>Photo by <a href="https://unsplash.com/@photoart2018?utm_source=medium&amp;utm_medium=referral">Andrew Buchanan</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>I try to spend some time each week practicing algorithms. Lately, I’ve been challenging myself to find solutions that are optimized for readability and clarity, not just time or space complexity. A well-written solution should be organized in a way that makes its key ideas as explicit as possible. Approaching algorithms this way helps me understand my solutions and explain them to others.</p><p>Let me illustrate this approach by applying it to the LeetCode problem <a href="https://leetcode.com/problems/first-missing-positive/">First Missing Positive</a>. Figuring this one out was a fascinating challenge. I’ll share my thought process and how I approached writing my solution.</p><h3>The Challenge</h3><p>Before we get started, I encourage you to take a shot at First Missing Positive yourself. For those who want to get straight to the explanation, here’s the challenge: you’re given an unordered array of integers and your goal is to find the smallest positive integer that doesn’t appear in the array. For instance, for the input [3, 4, -1, 1] we should return 2, since there’s a 1 in the array but not a 2. This isn’t that difficult to do, but here’s the catch: you’re supposed to do this in linear time while only using a constant amount of extra space.</p><p>This rules out the natural solution of sorting the array and then iterating over it looking for the missing number. This would work as follows:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/eec8cf4771873900c9617af25b239db8/href">https://medium.com/media/eec8cf4771873900c9617af25b239db8/href</a></iframe><p>But this attempt violates the constraint, since sorting the array takes more than linear time.</p><h3>Some Initial Observations</h3><p>I find that before attempting to write a solution, it helps to make general observations about the nature of the problem. These observations will end up playing a role in the finished solution, so it helps to consider them first on their own.</p><p>First, some numbers in the input array might not be relevant to determining the right answer. Any non-positive number won’t make a difference to determining the smallest missing positive, so it can safely be ignored. Also, any number larger than the length of the array can’t make a difference either — a number can only make a difference if there’s a sequential chain between it and 1, but there aren’t enough numbers to form such a chain if the number is larger than the length of the array.</p><p>Second, although it’s possible for duplicate numbers to show up, they’ll never make a difference to the smallest missing positive either. Once we find one instance of a number, the existence of more instances of that same number can safely be ignored.</p><p>Third, we’re going to have to use some amount of memory to keep track of the numbers we’ve seen while iterating over the array, and since we’re only allowed constant additional space we’ll be forced to reorder the initial array in place. Doing so in general is risky, since it might throw away valuable information. However, in this case the problem explicitly tells us that the initial array is unordered, so let’s presume that we can safely reorder it as we see fit.</p><h3>The Key Idea</h3><p>Sorting the array was a promising idea, but turned out to be too slow. But why assume that we need a <em>fully</em> sorted array? The key idea to solving the problem is that there’s a rearrangement procedure that both: (1) results in an array that’s <em>sorted enough</em> for us to find the smallest missing positive and (2) only takes linear time to run.</p><p>Specifically, what we need is a rearrangement that ensures the following: for any index <em>i</em>, if there’s at least one instance of the number <em>i</em> + 1 in the array, then index <em>i</em> has that number. For instance, if there’s a 2 somewhere in the array, then after the rearrangement a 2 should be at index 1.</p><p>If we can rearrange the array in this manner, we can find the smallest missing positive. All we have to do is iterate over the array until we find an unexpected number, and the index of that number will correspond to the smallest missing number. If we don’t find an unexpected number, then the array must be like [1, 2, 3] and we should just return the length of the array plus one. Here’s the idea in code:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/dbca40db1592ba9f588fc5d405f4391f/href">https://medium.com/media/dbca40db1592ba9f588fc5d405f4391f/href</a></iframe><p>This iteration takes linear time with no additional space complexity, so all that’s left is figuring out how to rearrange the numbers.</p><h3>Aligning Numbers with Indicies</h3><p>Here’s the procedure: we’ll iterate over the array and whenever we find a number that belongs at some other index in the array, we’ll swap it with the number that’s currently at that index. We may have to keep swapping multiple times for one index, but eventually we’ll get a number that doesn’t have to be swapped and then we’ll move on to the next index. Once we do this for every index in the array, the procedure is complete.</p><p>To see how this works, let’s start writing out some code to give us something more concrete to reason about:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/10e39b24b4bd3115c0f2826f7a18f180/href">https://medium.com/media/10e39b24b4bd3115c0f2826f7a18f180/href</a></iframe><p>For each index, we swap numbers until a certain condition fails to be met. Each time, we consider the target number at that index and potentially move it to a new destination. Note that we have to reset the target number and potential destination at the end of each pass through the while loop.</p><p>The code to swap two elements in an array is straightforward: you just use a temporary variable to store the first value, change the first value, and then change the second value. Let’s add that to our code:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ea91401c7f4b84ea435f8b2f4e87c3e5/href">https://medium.com/media/ea91401c7f4b84ea435f8b2f4e87c3e5/href</a></iframe><p>Okay, now what about the condition? First, we only want to swap a number if there’s a place in the array where that number belongs. This means we shouldn’t attempt to move a number that’s less than 1 or a number that’s greater than or equal the length of the array. Second, we only want to swap a number into a position if that position doesn’t already have the correct number in it. For instance, if we find a 5 but there’s already a 5 at index 4, then we should skip the extra 5 and leave it where it is.</p><p>All we have to do now is code up those conditions and use them. Here’s the function with everything added:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3b36bc43d5d90c5dcf0d7bdcd5ae0a84/href">https://medium.com/media/3b36bc43d5d90c5dcf0d7bdcd5ae0a84/href</a></iframe><p>Although it would be possible to save marginal amounts of memory by cutting out some of the extra helper methods and variable declarations, I prefer the function as it is, since it reads in a way that reflects the thought process behind the algorithm.</p><h3>Does Alignment take Linear Time?</h3><p>There’s one last point we need to get clear on before we conclude. In order to satisfy the constraints of the original problem, the function we just wrote has to run in linear time. But does it?</p><p>On the face of it, it would seem like it takes longer than linear time. As a general heuristic, whenever you have one loop inside of another you likely have a function that runs in quadratic time. We have a while loop inside of a for loop, so maybe we don’t have the right kind of solution after all.</p><p>However, consider two facts about our conditions from above. First, we only swap when a number will get placed at the appropriate index in the array. Second, once a number is placed at the appropriate index in the array, there’s no way for it to get swapped out of that position. Putting these two points together, we can conclude that the maximum number of times we could go through the while loop is equal to the length of the array. This means that, at most, we might have <em>n</em> steps from the while loop and <em>n</em> steps from the for loop, but that’s still just linear time.</p><h3>Conclusion</h3><p>Now that that we have the helper function we needed, all we have to do is put everything together. Here’s the finished product:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9d5f822964486b2a8e5725277d420868/href">https://medium.com/media/9d5f822964486b2a8e5725277d420868/href</a></iframe><p>This is a pretty verbose solution. Although you could rewrite it to be a bit more succinct, I prefer a more verbose solution when it’s self-documenting. All of the concepts that go into the solution are explicated as helper functions in the code itself. Because of this, reading the code gives you a summary of how it’s meant to work.</p><p>The first drafts of my algorithm solutions typically don’t come out this way. It definitely takes more work to find a solution that’s both correct and clear. I’ll admit that it can be hard to put in that work — practicing algorithms can feel like a game that you win by moving as quickly as you can. However, coding is a craft and I find that I get a lot more out of algorithm problems by slowing down and focusing on honing that craft. Give it a shot and see if it works for you too!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=90e6ed29ca81" width="1" height="1" alt=""><hr><p><a href="https://medium.com/swlh/how-to-solve-first-missing-positive-90e6ed29ca81">How to Solve First Missing Positive</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>
        <item>
            <title><![CDATA[Function Piping in JavaScript]]></title>
            <link>https://medium.com/@ian_grubb/function-piping-in-javascript-a125b0876a2b?source=rss-47e6201de8e0------2</link>
            <guid isPermaLink="false">https://medium.com/p/a125b0876a2b</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[functional-programming]]></category>
            <dc:creator><![CDATA[Ian Grubb]]></dc:creator>
            <pubDate>Mon, 05 Oct 2020 17:10:19 GMT</pubDate>
            <atom:updated>2020-10-05T17:10:19.593Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*_symkwLFlWw1mmO4" /><figcaption>Photo by <a href="https://unsplash.com/@samthewam24?utm_source=medium&amp;utm_medium=referral">Samuel Sianipar</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>It can be really valuable to learn a new programming language, even if the what you learn doesn’t become your language of choice for day-to-day coding. Learning a new language (especially one that’s built around a different paradigm than what you’re used to) exposes you to new concepts and approaches, making it a great way to grow as a programmer.</p><p>In this spirit, I recently took a deep dive into Elixir, a functional programming language with an interesting approach to concurrency. Elixir has a lot of cool features, but there’s one in particular that I really miss now that I’m mostly writing JavaScript: the pipe operator. JavaScript actually does have a pipeline operator as an <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Pipeline_operator">experimental feature</a>, but it’s not an official part of the language. Fortunately, we can make our own pipeline implementation and start using it right away.</p><h3>Why Use Pipes?</h3><p>The pipe operator makes it easier to write code that transforms data. Let’s say I have a number that I want to double, increase by five, and then divide by three. I have the number stored in a variable and I have a function for each data transformation:</p><pre>const number = 4<br>const double = x =&gt; x * 2<br>const addFive = x =&gt; x + 5<br>const divideByThree = x =&gt; x / 3</pre><p>How do I string these functions together to get the desired result? I could use intermediate variables:</p><pre>const doubledNumber = double(number)<br>const numberWithFive = addFive(doubledNumber)<br>const result = divideByThree(numberWithFive)</pre><p>but this approach isn’t ideal. Making a bunch of variables that you immediately abandon is pretty inelegant. The code also gets a bit hard to read, since you have to match up each of the variable definitions with the point where the variable gets used later in the code.</p><p>We can avoid the extra variables by nesting the functions:</p><pre>const result = divideByThree(addFive(double(number)))</pre><p>Unfortunately, the result is essentially unreadable. Everything is too densely packed and we have to read it backwards to see the actual sequence of transformations that get applied to the initial number.</p><p>Here’s what we could do if we had a pipeline operator:</p><pre>const result = <br>  number<br>  |&gt; double<br>  |&gt; addFive<br>  |&gt; divideByTwo</pre><p>Here’s how it works: you put your initial value before the first pipe and you put each function that needs to be called after a pipe. The return value of each function automatically gets passed as an argument to the next function, until the last function returns the ultimate value. So we get the computation we want, without extra variables or dense, backwards nesting.</p><h3>Implementing Pipes</h3><p>So how do we implement pipes in JavaScript? There are actually a few options, which have different pros and cons.</p><h4>Using Babel</h4><p>JavaScript doesn’t support the pipeline syntax used above, but if you like that syntax you can use it and then transpile what you write into valid JavaScript code. You would do this by setting up Babel and using their plugin that implements the JavaScript pipeline proposal. Babel can be a bit confusing for beginners, but if you’re comfortable this is definitely a good option to check out. My focus here is on how to code our own pipes from scratch, but if you’re interested in using Babel you should check out <a href="https://medium.com/@prudywsh/babel-7-pipeline-operator-in-javascript-a7724212b8ba">this</a> resource.</p><h4>Using a Higher-Order Function</h4><p>On this approach, the pipeline operator is a higher-order function that takes in a sequence of functions and returns a single function that combines them all. The function has a remarkably succinct definition. It takes a sequence of functions and combines them with the reduce method:</p><pre>const combine = (result, nextFun) =&gt; nextFun(result)<br>const pipe = (...funs) =&gt; x =&gt; funs.reduce(combine, x)</pre><p>The ...funs argument allows pipe to accept an arbitrary number of functions as an input and stores them in an array in the variable funs. It then returns a function that takes a value x and returns the result of passing x through each of the functions in funs. This is where it uses the reduce method, which keeps track of a value (starting at x) and iterates over funs, updating the value at each step by plugging it into the member of funs for that step.</p><p>At this point, we can perform the original calculation with the expression:</p><pre>const result = pipe(double, addFive, divideByThree)(number)</pre><p>The only significant difference between this and the pipeline operator is that the data that gets piped gets passed in at the end. However, we can fix that by making another function that itself calls pipe:</p><pre>const usingPipe = (value, ...functions) =&gt; pipe(...functions)(value)</pre><p>With this function, you can calculate the result as follows:</p><pre>const result = usingPipe(2, double, addFive, divideByThree)</pre><p>giving us a version of the pipeline operator where the data and functions are all lined up in the correct order.</p><p>This approach has one notable limitation: it only pipes together functions that take a single argument. This can be an inconvenience, since you might want to call a multi-argument function in order to pipe one of its arguments into a new return value. If you want to use a multi-argument function with pipe, you have to first curry it so that it only accepts a single argument.</p><h4>Using a Value Wrapper</h4><p>There’s an alternative implementation of the pipeline operator, which has us call pipe on the value we want to pipe, rather than the functions that the value is meant to be piped through. Calling pipe on the value returns a wrapped version of that value, which allows us to pass in callbacks that update the value (giving us something analogous to a Promise).</p><p>Here’s an initial take on this version of the pipeline operator:</p><pre>const pipe = value =&gt; ({<br>  value,<br>  to: cb =&gt; pipe(cb(value))<br>})</pre><p>It takes a value and returns an object that contains the value, but also a to method that can accept a callback that it uses to update the value. Because to then wraps the value in a new pipe, we can chain this method with itself indefinitely. Here’s an example:</p><pre>const result =<br>  pipe(2)<br>  .to(double)<br>  .to(addFive)<br>  .to(divideByThree)<br>  .value</pre><p>Notice that we have to call .value at the end of chain, since we ultimately want to get the unwrapped version of the value in the pipe.</p><p>This implementation is a bit more verbose than the implementation using a higher-order function. Although this requires a bit more typing on our part, it also gives us a bit more control over how values move through the pipe. We can use this to tweak pipe so that to accepts functions with multiple arguments:</p><pre>const pipe = value =&gt; ({<br>  value,<br>  to: (cb, ...args) =&gt; pipe(cb(value, ...args))<br>})</pre><p>Whenever a function takes multiple arguments, the first argument is the value from the pipe, while the remaining arguments are passed along with the callback. Here’s an example of this version of pipe in action:</p><pre>const add = (x, y) =&gt; x + y<br>const divide = (x, y) =&gt; x / y<br>const multiple = (x, y) =&gt; x * y</pre><pre>const value = <br>  pipe(2)<br>  .to(multiply, 2) // x is the piped 2, y is 2<br>  .to(add, 5).     // x is the piped 4, y is 5<br>  .to(divide, 3)   // x is the piped 9, y is 3<br>  .value</pre><p>This is actually how pipes work in Elixir. While this approach is more verbose, I enjoy not having to curry all of the functions I want to use within the pipe.</p><p>Ultimately, it’s interesting to know that there are different ways of implementing a pipeline in JavaScript. Whichever you prefer, I encourage you to give pipes a try!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a125b0876a2b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[First-Class Functions in JavaScript]]></title>
            <link>https://medium.com/@ian_grubb/first-class-functions-in-javascript-fe6caf61d179?source=rss-47e6201de8e0------2</link>
            <guid isPermaLink="false">https://medium.com/p/fe6caf61d179</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[functional-programming]]></category>
            <dc:creator><![CDATA[Ian Grubb]]></dc:creator>
            <pubDate>Mon, 28 Sep 2020 13:15:05 GMT</pubDate>
            <atom:updated>2020-09-28T14:07:18.293Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*jkDI1-E3xWngzqrA" /><figcaption>Photo by <a href="https://unsplash.com/@jannerboy62?utm_source=medium&amp;utm_medium=referral">Nick Fewings</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>JavaScript is a multi-paradigm programming language that allows certain functional programming techniques. It does this by supporting the use of first-class functions — functions that can be stored in variables and treated like data. JavaScript functions can even be passed to other functions as inputs, and they can be returned from other functions as outputs. This is a seemingly small feature, but it can have enormous consequences for how you write code.</p><p>Unfortunately, many JavaScript newcomers have a hard time understanding the functional side of the language. Functional programming requires concepts and techniques that you won’t necessarily have encountered before, even if you have a significant background in object-oriented programming.</p><p>Nonetheless, learning functional programming can make you a better JavaScript developer. Whether you’re working on a vanilla JavaScript app, an app in a front-end framework like React, or a back-end built with Node, functional techniques can be used to build new features and write cleaner code. So if you want to learn more about functional JavaScript, join me in this quick crash course.</p><h3>Putting Functions into Functions</h3><p>Because JavaScript supports first-class functions, it lets us write functions that accept other functions as arguments. These functions that get passed into other functions are typically referred to as <em>callbacks</em>. Passing a callback into another function allows us to tell that function what code to run at certain points in its execution. Let’s look at a couple of the cases where callbacks are useful.</p><h4>Controlling Asynchronous Behavior</h4><p>Perhaps the most common use for callbacks is controlling code that should get executed at some point in the future. Consider the following function, which starts a timer and logs a message once time is up:</p><pre>const sendDelayedMessage = (message, seconds) =&gt; {<br>  const sendMessage = () =&gt; console.log(message)<br>  setTimeout(sendMessage, seconds * 1000)<br>}</pre><p>In this example, the setTimeout function expects a callback, which acts like a plan for what to do after the specified number of seconds has elapsed. That plan is represented by sendMessage, which is passed as an argument to setTimeout.</p><p>Note that sendMessage couldn’t have just been console.log(message).That would have logged the message immediately and left sendMessage undefined. It may look a bit weird have the arrow and empty parentheses as part of sendMessage, but they are essential in order to delay the execution of console.log. Functions like this are sometimes referred to as <em>thunks</em>, and it’s not uncommon to have to thunk parts of your code so that you can have control over when it gets executed.</p><h4>Working with Array Methods</h4><p>Callbacks are also useful when working with iteration methods like map and filter. All of these methods accept a callback function and then call that callback for each element in the array that they’re called on. What sets them apart from each other is what they do with the return values that they get from the callback.</p><p>The map method makes a 1-to-1 mapping between the elements of the original array and elements of a new array. For instance, the code [1, 2, 3].map(x =&gt; x + 1) returns the array [2, 3, 4] — every number in the new array is 1 plus the corresponding number in the previous array. Under the hood, map makes a new array, calls the function x =&gt; x + 1 on every number in the old array, and pushes each of the return values into the new array.</p><p>The filter method works a bit differently. Its purpose is to select a subset of the elements in the initial array, based on whether they satisfy some condition. To do this, it calls the callback function on each element in the array and check whether it returns a truthy value. In other words, the callback function acts as a condition that array elements can either satisfy or not. As an example, a call like [1, 2, 3].filter(x =&gt; x % 2 === 1) returns [1, 3], which are the odd elements found in the initial array.</p><p>Array methods like map and filter illustrate how a functional approach can lead to cleaner code. Iterating with for loops tends to be pretty verbose and requires code that gets repeated for many other for loops. Array methods hide that repeated code, resulting in programs that are more succinct and easier to read.</p><h4>Designing Functions that Receive Callbacks</h4><p>In the examples so far, we’ve designed callbacks that would achieve an intended effect when passed to pre-built JavaScript functions. However, you should also look out for cases where you can prevent code duplication by writing functions designed to accept callbacks.</p><p>Let’s take inspiration from the array methods we just looked at and write one of our own. I’m going to write a function that takes the elements in an array and groups them according to an attribute type of my choice. For instance, I should be able to take the array [&quot;I &lt;3 functional programming”, “Arrows are great&quot;, &quot;Learn functional JavaScript&quot;] and group these sentences by their word counts, returning the object {3: [“Arrows are great&quot;, &quot;Learn functional JavaScript&quot;], 4: [&quot;I &lt;3 functional programming”]}.</p><p>I can do this with a function that accepts an array and a callback as arguments. It loops over the array and calls the callback for every element, building up a grouping object one element at a time:</p><pre>const groupBy = (array, callback) =&gt; {<br>  const grouping = {}<br>  for (let i = 0; i &lt; array.length; i++){<br>    const value = array[i]<br>    const key = callback(value)<br>    if (grouping[key]){<br>      grouping[key].push(value)<br>    } else {<br>      grouping[key] = [value]<br>    }<br>  }<br>  return grouping<br>}</pre><p>We could now use this function as follows:</p><pre>const getWordCount = string =&gt; string.split(&quot; &quot;).length<br>const sentences = [&quot;I &lt;3 functional programming”, “Arrows are great&quot;, &quot;Learn functional JavaScript&quot;]</pre><pre>groupBy(sentences, getWordCount)</pre><p>and it would return the sentences grouped by word count.</p><h3>Getting Functions Out of Functions</h3><p>We can also write functions that return functions as their outputs. These returned functions can then be saved in variables and used elsewhere in a program. This means that rather than writing all of a program’s functions prior to runtime, we can write certain functions that dynamically generate other functions as our code executes.</p><h4>Currying</h4><p>Here’s an interesting consequence of allowing functions to return functions: it makes it possible to rewrite any program so that each of the functions in the program has at most one argument. This is possible because of a technique known as <em>currying</em>.</p><p>It’s easiest to see how this works with an example. If we started with the function const addNormal = (x, y) =&gt; x + y, we could curry it by keeping the return value the same but splitting the arguments up with multiple arrows: const addCurried = x =&gt; y =&gt; x + y. This curried function takes a number and returns the function y =&gt; x + y, which then takes a second number and returns a sum. Both functions allow us to add two numbers, they’re just called in slightly different ways:</p><pre>addNormal(5, 7)<br>// 12<br>addCurried(5)(7)<br>// 12</pre><p>As you can see, the normal function accepts its arguments as a pair, while the curried function accepts its arguments one after another.</p><p>Curried functions give us added flexibility, since they let us apply some but not all of the arguments to a function. We have the option of passing addCurried 5 and 7 together, but we could also just pass 5 and hold off on passing the second argument. Instead, we would store the intermediate function in a variable and then call this function later on:</p><pre>const addFive = addCurried(5)<br>addFive(7)<br>// 12</pre><p>Now we have a special type of adding function that we can use multiple times across a program, potentially helping us clean up our code.</p><h4>Closures</h4><p>Let’s look more closely at how currying is possible. The addFive function behaves like the function y =&gt; 5 + y. However, that’s not what addFive actually looks like — if you were to log it, you’d see the result y =&gt; x + y. So how can this function act like y =&gt; 5 + y?</p><p>The answer has to do with the concept of <em>closure</em>. When a function gets defined, it has access to the variables in the surrounding environment. If it references a variable that’s defined outside of its own scope, it remembers the variable and can reference the value in the future when the function is called. This means it’s best not to think of addFive as just the function y =&gt; x + y, but rather this function <em>and</em> a reference to the variable x. Since the variable continues to hold the value 5, it gets substituted into the function whenever it gets called.</p><p>It’s worth emphasizing that a closure remembers the variable it references, not the value that was stored in the variable when the function was defined. It’s hard to appreciate the difference in the previous case, since x is a constant that will always contain the value 5. However, it’s also possible to create a closure that points to some mutable state, resulting in a function that can change its behavior over time.</p><p>To illustrate this concept, let’s make a function that returns a counter function. The counter function it returns should simply return the number of times it has been called whenever it gets called. Here’s the function:</p><pre>const makeCounter = () =&gt; {<br>  let count = 0<br>  return () =&gt; count++<br>}</pre><p>The returned function () =&gt; count++ references the variable count, which is defined outside of its scope. It also mutates the value of that variable, meaning that () =&gt; count++ won’t always have the same return value. Here’s how you might use makeCounter:</p><pre>const counterOne = makeCounter()</pre><pre>counterOne()<br>// 1<br>counterOne()<br>// 2</pre><pre>const counterTwo = makeCounter()</pre><pre>counterTwo()<br>// 1<br>counterOne()<br>// 3</pre><p>So makeCounter functions as an initializer that you call to return a counter that you can save in a variable. The counters it makes keep track of their value over time, but different counters enclose different counter variables, meaning that they increase independently of each other.</p><h3>Functions that Enhance Other Functions</h3><p>To conclude, let’s look at some functions that have other functions as both inputs <em>and</em> outputs. You can use these kinds of higher-order functions to take in ordinary functions and return versions of those functions that have been enhanced in various ways.</p><p>I’ll start with a function that lets us time how long it takes for some other function to finish executing. This could be useful for testing code performance. What we need is a function that takes a callback and returns a modified function. The modified function should start a timer, call the callback function with its arguments, report how much time has elapsed, and then return the callback’s return value:</p><pre>const addTimer = callback =&gt; {<br>  return (...args) =&gt; {<br>    const initialTime = Date.now()<br>    const returnValue = callback(...args)<br>    console.log(`Duration: ${Date.now()- initialTime}ms`)<br>    return returnValue<br>  }<br>}</pre><p>A handy trick here is using ...args, which will match any number of arguments passed into a function and put them into an array. This lets us build a general-purpose addTimer function that can add a timer to a function with any number of arguments.</p><p>It might also be useful to have functions that track how they get used in an application. We can do this by writing a function that updates another function to keep track of its own call history:</p><pre>const trackHistory = callback =&gt; {<br>  const history = []<br>  return (...args) =&gt; {<br>    const returnValue = callback(...args)<br>    history.push({ arguments: args, result: returnValue})<br>    console.log(history)<br>    return returnValue<br>  }<br>}</pre><p>This higher-order function declares a history variable outside the scope of the returned function, so that this function can remember its old calls and push data about these calls whenever they happen. Here’s an illustration of what this can do in practice:</p><pre>const add = (x, y) =&gt; x + y<br>const trackedAdd = trackHistory(add)</pre><pre>trackedAdd(1, 2)<br>// logs: [{arguments: [1, 2], result: 3}]<br>trackedAdd(5, 7)<br>// logs: [{arguments: [1, 2], result: 3}, {arguments: [5, 7], result: 12}]</pre><p>This could be useful for debugging, or even the basis for a rudimentary caching strategy.</p><p>We can actually improve on this technique. It’s annoying that the current function logs its history in every case, and it would be great to have separate ways to view and control the history. We can do that with this higher-order function:</p><pre>const controlledTracking = callback =&gt; {<br>  let history = []<br>  const updatedFunction = (...args) =&gt; {<br>    const returnValue = callback(...args)<br>    history.push({ arguments: args, result: returnValue})<br>    return returnValue<br>  }<br>  const report = () =&gt; console.log(history)<br>  const clear = () =&gt; history = []<br>  return [updatedFunction, report, clear]<br>}</pre><p>The basic strategy is the same as before, only now we define three functions and return them all in an array. You can use these as follows:</p><pre>const add = (x, y) =&gt; x + y<br>const [controlledAdd, report, clear] = controlledTracking(add)</pre><pre>controlledAdd(1, 2)<br>controlledAdd(5, 7)<br>report()<br>// logs: [{arguments: [1, 2], result: 3}, {arguments: [5, 7], result: 12}]<br>clear()<br>report()<br>// logs: []</pre><p>For convenience, we’re defining the trio of functions by pattern matching on the array returned by controlledTracking. This gives us an automatically caching version of the original function, a function to view the current state of the cache, and a function to clear the cache.</p><p>Finally, let’s return to the topic of currying. We can always manually curry functions ourselves, but it’s more convenient to have a higher-order function that automatically curries other functions for us:</p><pre>const curry = callback =&gt; {<br>  const recursiveReturn = currentArgs =&gt; nextArg =&gt; {<br>    const newArgs = [...currentArgs, nextArg]<br>    if (newArgs.length &gt;= callback.length) {<br>      return callback(...newArgs)<br>    } else {<br>      return recursiveReturn(newArgs)<br>    }<br>  }<br>  return recursiveReturn([])<br>}</pre><p>The output function lets us feed in arguments over time and save them to an array whenever we do. Whenever the array doesn’t contain enough arguments to call the callback function, the function just returns a copy of itself, except that the copy knows about the new argument. Once there are enough elements in the array, the callback function gets called with elements of the array as its arguments.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fe6caf61d179" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A Guide to CSS Position]]></title>
            <link>https://medium.com/@ian_grubb/a-guide-to-css-position-f5323b154bd4?source=rss-47e6201de8e0------2</link>
            <guid isPermaLink="false">https://medium.com/p/f5323b154bd4</guid>
            <category><![CDATA[layout]]></category>
            <category><![CDATA[css]]></category>
            <category><![CDATA[css-position]]></category>
            <dc:creator><![CDATA[Ian Grubb]]></dc:creator>
            <pubDate>Mon, 14 Sep 2020 20:45:47 GMT</pubDate>
            <atom:updated>2020-09-14T20:45:47.449Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ycn0ydZRSZjGKUev" /><figcaption>Photo by <a href="https://unsplash.com/@halacious?utm_source=medium&amp;utm_medium=referral">Halacious</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Building layouts is an important but challenging aspect of front-end development. Given this, it’s no surprise that CSS has a lot of layout-building tools to choose from. I’ll be talking about one of them here: the position property. This is a powerful tool that can create some impressive effects, but it’s also easily misunderstood and misused. There’s so much that I wish I had known when I was first learning CSS, and I’m going to try to share as much as I can. Let’s get started!</p><h3>Ways to Position with CSS</h3><p>We’ll start by looking at the ways of positioning HTML elements through CSS. There are five options: static, relative, fixed, absolute, and sticky.</p><h4>Static Position</h4><p>HTML elements are statically positioned by default. Statically positioned elements participate in the normal flow of an HTML document. This means that block elements will stack on top of each other and inline elements will sit next to each other on a line and wrap to the next line as necessary.</p><p>These are sensible defaults-they provide a minimal viable layout that’s at least somewhat usable. We can use non-static positioning to make exceptions to these defaults, modifying how an element interacts with the normal flow or even removing it from the normal flow entirely. Doing so is risky, since the defaults are what they are for good reason. But when done carefully, modifications to the normal document flow can significantly enhance a site.</p><p>CSS provides a set of additional properties for making these adjustments: top, bottom, left, right, and z-index. The first four are used to move an element around the page and z-index is used to determine which of two overlapping contents shows on top of the other. All five of these properties are disabled on statically positioned elements.</p><h4>Relative Position</h4><p>Relative positioning keeps an element within the normal flow, but allows us to push it in some direction relative to where it would have been. Whatever space relative elements would have taken up still counts as occupied, so they still displace other elements. This makes relative positioning only a minor deviation from the normal flow.</p><p>Here’s an example of how this works. We have five squares aligned by a flex parent. The purple square has relative positioning, at top value of 15px, a left value of -10px, and a z-index of -1:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcodepen.io%2Fiangrubb%2Fembed%2Fpreview%2FyLemEEE%3Fheight%3D600%26slug-hash%3DyLemEEE%26default-tabs%3Dcss%2Cresult%26host%3Dhttps%3A%2F%2Fcodepen.io&amp;display_name=CodePen&amp;url=https%3A%2F%2Fcodepen.io%2Fiangrubb%2Fpen%2FyLemEEE&amp;image=https%3A%2F%2Fassets.codepen.io%2F4260516%2Finternal%2Fscreenshots%2Fpens%2FyLemEEE.default.png%3Ffit%3Dcover%26amp%3Bformat%3Dauto%26amp%3Bha%3Dfalse%26amp%3Bheight%3D360%26amp%3Bquality%3D75%26amp%3Bv%3D2%26amp%3Bversion%3D1596303364%26amp%3Bwidth%3D640&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=codepen" width="800" height="600" frameborder="0" scrolling="no"><a href="https://medium.com/media/678915a9898b1ac0ddec0ae16ebcb40a/href">https://medium.com/media/678915a9898b1ac0ddec0ae16ebcb40a/href</a></iframe><p>As a result, the purple square moves down 15px from its normal position and left 10px from its normal position. Elements are treated as having a z-index of 0 by default, so the purple square’s lower z-index pushes it back behind the green square that it overlaps.</p><h4>Fixed Position</h4><p>Elements with fixed position are taken out of the normal flow of the document entirely, meaning they don’t displace other elements. They’re then placed in relation to the user’s viewport, so that they won’t move around the screen as the user scrolls.</p><p>If you assign a value to the top property, it fixes the top of the element the specified distance from the top of the viewport. Likewise for bottom, left, and right. By applying the correct z-index values, elements in the normal flow can be made to scroll under or over fixed elements. In this example, the green squares scroll over a fixed background div and under a fixed header:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcodepen.io%2Fiangrubb%2Fembed%2Fpreview%2FVweodNa%3Fheight%3D600%26slug-hash%3DVweodNa%26default-tabs%3Dcss%2Cresult%26host%3Dhttps%3A%2F%2Fcodepen.io&amp;display_name=CodePen&amp;url=https%3A%2F%2Fcodepen.io%2Fiangrubb%2Fpen%2FVweodNa&amp;image=https%3A%2F%2Fassets.codepen.io%2F4260516%2Finternal%2Fscreenshots%2Fpens%2FVweodNa.default.png%3Ffit%3Dcover%26amp%3Bformat%3Dauto%26amp%3Bha%3Dfalse%26amp%3Bheight%3D360%26amp%3Bquality%3D75%26amp%3Bv%3D2%26amp%3Bversion%3D1598838884%26amp%3Bwidth%3D640&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=codepen" width="800" height="600" frameborder="0" scrolling="no"><a href="https://medium.com/media/ad763c9f489dd3a94a6be0cdb3d44ee9/href">https://medium.com/media/ad763c9f489dd3a94a6be0cdb3d44ee9/href</a></iframe><h4>Absolute Position</h4><p>Like fixed position, absolute position takes an element out of the normal flow and gives us control over its placement. The difference is that instead of positioning in relation to the viewport, it allows for positioning in relation to one of its ancestors in the HTML tree.</p><p>The rules determining which ancestor gets used are a bit tricky. If an absolutely positioned element has at least one ancestor with a non-static position, then it will be positioned in relation to the <em>nearest</em> such ancestor above it in the tree. Otherwise, it will be placed in relation to the body of the document.</p><p>Sometimes beginners confuse absolute and fixed positioning. In the next example, there are two elements with a top value of 10px. One’s fixed and one’s absolute, but at first glance there doesn’t seem to be any difference between the two results. However, scrolling the container produces a difference:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcodepen.io%2Fiangrubb%2Fembed%2Fpreview%2FwvMbNzr%3Fheight%3D600%26slug-hash%3DwvMbNzr%26default-tabs%3Dcss%2Cresult%26host%3Dhttps%3A%2F%2Fcodepen.io&amp;display_name=CodePen&amp;url=https%3A%2F%2Fcodepen.io%2Fiangrubb%2Fpen%2FwvMbNzr&amp;image=https%3A%2F%2Fassets.codepen.io%2F4260516%2Finternal%2Fscreenshots%2Fpens%2FwvMbNzr.default.png%3Ffit%3Dcover%26amp%3Bformat%3Dauto%26amp%3Bha%3Dfalse%26amp%3Bheight%3D360%26amp%3Bquality%3D75%26amp%3Bv%3D2%26amp%3Bversion%3D1595991037%26amp%3Bwidth%3D640&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=codepen" width="800" height="600" frameborder="0" scrolling="no"><a href="https://medium.com/media/d22a97aad7ec010e6e78004dd8f3ef6c/href">https://medium.com/media/d22a97aad7ec010e6e78004dd8f3ef6c/href</a></iframe><p>The absolute element is positioned in relation to the body of the document, which is taller than the height of the viewport. As such, scrolling moves the absolute element up so that it can stay 10px from the top of the body of the document, while the fixed element remains fixed 10px from the top of the viewport.</p><h4>Sticky Position</h4><p>Sticky is a relatively new kind of positioning, which works as a kind of hybrid between relative and fixed. It offers a powerful effect that could only previously be accomplished through JavaScript.</p><p>A sticky element scrolls into the user’s viewport as though it has a relative position. But once it reaches the edge of the viewport it temporarily behaves as though it has a fixed position. It only scrolls off of the screen once its parent starts to scroll off of the screen as well. Here’s the effect in action:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcodepen.io%2Fiangrubb%2Fembed%2Fpreview%2FExPqpdy%3Fheight%3D600%26slug-hash%3DExPqpdy%26default-tabs%3Dcss%2Cresult%26host%3Dhttps%3A%2F%2Fcodepen.io&amp;display_name=CodePen&amp;url=https%3A%2F%2Fcodepen.io%2Fiangrubb%2Fpen%2FExPqpdy&amp;image=https%3A%2F%2Fassets.codepen.io%2F4260516%2Finternal%2Fscreenshots%2Fpens%2FExPqpdy.default.png%3Ffit%3Dcover%26amp%3Bformat%3Dauto%26amp%3Bha%3Dfalse%26amp%3Bheight%3D360%26amp%3Bquality%3D75%26amp%3Bv%3D2%26amp%3Bversion%3D1598322781%26amp%3Bwidth%3D640&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=codepen" width="800" height="600" frameborder="0" scrolling="no"><a href="https://medium.com/media/49f95e9dd442b0cacc3b00e9faeb7747/href">https://medium.com/media/49f95e9dd442b0cacc3b00e9faeb7747/href</a></iframe><p>In order for this to work, the sticky element must have a top, bottom, left, or right property, depending on which edges the element should stick to. In this example, the header is sticky and its top and left values are 0, which makes it stick to the top or left when scrolled down or right. It’s also possible to set other values besides 0 if you want part of the sticky element off-screen or a gap between the sticky element and the edge of the screen.</p><h3>Techniques for Using Positioned Elements</h3><p>Using positioned elements effectively can be a challenge. Let’s look at a few techniques that make it easier to get positioned elements to do what you want them to do.</p><h4>Positioning in Relation to a Parent</h4><p>Suppose you want to place a child element at a certain location on top of its parent, so that it remains in that location no matter how the parent element adjusts in size and shape due to its place in the document. There’s a combination of position assignments that allows you to do this. First, make the child position absolute and give it whatever top, bottom, left, or right attributes you need. Second, make the parent position relative. This illustrates the difference between a static and a relative parent:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcodepen.io%2Fiangrubb%2Fembed%2Fpreview%2FjOWoGKX%3Fheight%3D600%26slug-hash%3DjOWoGKX%26default-tabs%3Dcss%2Cresult%26host%3Dhttps%3A%2F%2Fcodepen.io&amp;display_name=CodePen&amp;url=https%3A%2F%2Fcodepen.io%2Fiangrubb%2Fpen%2FjOWoGKX&amp;image=https%3A%2F%2Fassets.codepen.io%2F4260516%2Finternal%2Fscreenshots%2Fpens%2FjOWoGKX.default.png%3Ffit%3Dcover%26amp%3Bformat%3Dauto%26amp%3Bha%3Dfalse%26amp%3Bheight%3D360%26amp%3Bquality%3D75%26amp%3Bv%3D2%26amp%3Bversion%3D1595990898%26amp%3Bwidth%3D640&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=codepen" width="800" height="600" frameborder="0" scrolling="no"><a href="https://medium.com/media/82919b91df578af1de0bd00e2dc21134/href">https://medium.com/media/82919b91df578af1de0bd00e2dc21134/href</a></iframe><p>Relative positioning achieves two goals in this case. Obviously it allows the child to be positioned in relation to the parent. But it also does this without disrupting the parent’s own behavior. A position relative parent still reserves a space in the normal flow of the document, so as long as you don’t give it a value for top, bottom, left, right, or z-index, it will behave exactly like a statically positioned element.</p><h4>Centering Elements</h4><p>When you have an absolutely positioned child, you sometimes want it perfectly centered within its parent. The trick to getting this working depends on the fact that percentage unit work differently in different contexts. In the context of properties like top, the percentage unit depends on the size of the parent of the element we’re styling. But in the context of a translation, the percentage unit depends on the size of the element itself.</p><p>This means you can center an element within its parent by determining its location in <em>both</em> ways at once. Here are the stages in the process:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcodepen.io%2Fiangrubb%2Fembed%2Fpreview%2FVwaZYwy%3Fheight%3D600%26slug-hash%3DVwaZYwy%26default-tabs%3Dcss%2Cresult%26host%3Dhttps%3A%2F%2Fcodepen.io&amp;display_name=CodePen&amp;url=https%3A%2F%2Fcodepen.io%2Fiangrubb%2Fpen%2FVwaZYwy&amp;image=https%3A%2F%2Fassets.codepen.io%2F4260516%2Finternal%2Fscreenshots%2Fpens%2FVwaZYwy.default.png%3Ffit%3Dcover%26amp%3Bformat%3Dauto%26amp%3Bha%3Dfalse%26amp%3Bheight%3D360%26amp%3Bquality%3D75%26amp%3Bv%3D2%26amp%3Bversion%3D1596405189%26amp%3Bwidth%3D640&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=codepen" width="800" height="600" frameborder="0" scrolling="no"><a href="https://medium.com/media/96186e05cc45091974b49fba99e0e43a/href">https://medium.com/media/96186e05cc45091974b49fba99e0e43a/href</a></iframe><p>The first purple square has position absolute, but it’s just in its default position of top and left 0. The second purple square has top and left values of 50%, putting its top-left corner at its parent’s center. The third purple square has the same top and left values, but also a transformation to translate it -50% vertically and horizontally. This moves it up and to the left so that it’s centered perfectly within its parent.</p><h4>Determining Size with Top + Bottom or Left + Right</h4><p>You’ll sometimes want a positioned child to span across some portion of its parent. For instance, in the example below we want a child to extend across its parent leaving 8px to the left, 16px to the right, 8px to the top, and half of the parent’s height to the bottom. This can be done by setting top and left to 8px each, and then setting width and height using the appropriate calculations. But there’s an easier way: we can set width by combining top and bottom, and we can set width by combining left and right. Here are both ways of achieving the same effect:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcodepen.io%2Fiangrubb%2Fembed%2Fpreview%2FKKzPpzm%3Fheight%3D600%26slug-hash%3DKKzPpzm%26default-tabs%3Dcss%2Cresult%26host%3Dhttps%3A%2F%2Fcodepen.io&amp;display_name=CodePen&amp;url=https%3A%2F%2Fcodepen.io%2Fiangrubb%2Fpen%2FKKzPpzm&amp;image=https%3A%2F%2Fassets.codepen.io%2F4260516%2Finternal%2Fscreenshots%2Fpens%2FKKzPpzm.default.png%3Ffit%3Dcover%26amp%3Bformat%3Dauto%26amp%3Bha%3Dfalse%26amp%3Bheight%3D360%26amp%3Bquality%3D75%26amp%3Bv%3D2%26amp%3Bversion%3D1596407733%26amp%3Bwidth%3D640&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=codepen" width="800" height="600" frameborder="0" scrolling="no"><a href="https://medium.com/media/0172438e640b6db4ccef71ce221cfbfa/href">https://medium.com/media/0172438e640b6db4ccef71ce221cfbfa/href</a></iframe><p>Of the two options, setting width and height implicitly strikes me as the cleaner, more readable option.</p><h4>Uncovering Content from Fixed Navigation</h4><p>Fixed headers can be convenient, since they ensure that navigation options are always readily available to the user. However, since they can cover up content they should be used with care-you don’t want to make information hard or even impossible to access.</p><p>A good first step is to apply a margin to the top of the element that contains the obstructing navigation. Setting the margin to the same height as the navigation bar prevents content at the very top of your page from being inaccessible.</p><p>However, applying a margin doesn’t fully solve the problem. If you use anchor links on a page with a fixed header, the links will scroll the page so that the navigation starts out on top of whatever header you linked to (you can find an example and discussion of the problem <a href="https://www.seowebdesignllc.com/fixed-headers-and-jump-links-the-solution-is-scroll-margin-top/">here</a>). That’s a bit sloppy and not the best user experience. Here’s an example where the problem is solved:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcodepen.io%2Fiangrubb%2Fembed%2Fpreview%2FJjXPdNx%3Fheight%3D600%26slug-hash%3DJjXPdNx%26default-tabs%3Dhtml%2Cresult%26host%3Dhttps%3A%2F%2Fcodepen.io&amp;display_name=CodePen&amp;url=https%3A%2F%2Fcodepen.io%2Fiangrubb%2Fpen%2FJjXPdNx&amp;image=https%3A%2F%2Fassets.codepen.io%2F4260516%2Finternal%2Fscreenshots%2Fpens%2FJjXPdNx.default.png%3Ffit%3Dcover%26amp%3Bformat%3Dauto%26amp%3Bha%3Dfalse%26amp%3Bheight%3D360%26amp%3Bquality%3D75%26amp%3Bv%3D2%26amp%3Bversion%3D1596410034%26amp%3Bwidth%3D640&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=codepen" width="800" height="600" frameborder="0" scrolling="no"><a href="https://medium.com/media/96b87ba14bcd9c93b64f3b0a4484eba7/href">https://medium.com/media/96b87ba14bcd9c93b64f3b0a4484eba7/href</a></iframe><p>The trick is to apply a scroll-margin to the top of each heading that you use as an anchor link. In this case, I added enough margin to account for the navigation bar and still leave a bit of breathing room above the heading.</p><h4>Controlling Overlap through HTML Structure</h4><p>The next technique helps control how elements overlap when you use the z-index property. Here’s a fact that’s surprising to a lot of people who haven’t dealt with it before: you can’t always force one non-static element above another just by setting the z-index values of the elements. The reason is that z-index values don’t get compared across the whole document, only across a specific <em>stacking context</em>.</p><p>This actually gets pretty complicated, so let’s just start with an example. Below, we have a single bar with z-index 2 and two pairs of elements. For each pair, the larger square has a z-index of 1 and the smaller square has a z-index of 3. I’ve set the squares to move past the bar when hovered over. We’d expect that for each pair, the large square would go under the bar and while the small square would go over. But that’s not the behavior we actually get:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcodepen.io%2Fiangrubb%2Fembed%2Fpreview%2FQWyeXaz%3Fheight%3D600%26slug-hash%3DQWyeXaz%26default-tabs%3Dcss%2Cresult%26host%3Dhttps%3A%2F%2Fcodepen.io&amp;display_name=CodePen&amp;url=https%3A%2F%2Fcodepen.io%2Fiangrubb%2Fpen%2FQWyeXaz&amp;image=https%3A%2F%2Fassets.codepen.io%2F4260516%2Finternal%2Fscreenshots%2Fpens%2FQWyeXaz.default.png%3Ffit%3Dcover%26amp%3Bformat%3Dauto%26amp%3Bha%3Dfalse%26amp%3Bheight%3D360%26amp%3Bquality%3D75%26amp%3Bv%3D2%26amp%3Bversion%3D1596406025%26amp%3Bwidth%3D640&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=codepen" width="800" height="600" frameborder="0" scrolling="no"><a href="https://medium.com/media/3d442487cd0b2c0c1659dbf161bbeb75/href">https://medium.com/media/3d442487cd0b2c0c1659dbf161bbeb75/href</a></iframe><p>Ok, so what’s going on? The key difference between the two sides is HTML structure. In the first example, the large square contains the smaller square as a child. This ensures that when the hover translation causes the large square to move, the small square moves along with it. But because there’s a z-index on the large square, it creates a new stacking context. This means that anything above the large square will automatically be above any of its children (even the small square with a z-index of 3).</p><p>This is a surprising and potentially frustrating rule. But the rule can also be quite valuable, since its good to have safeguards against an element showing up where it shouldn’t be if given the wrong z-index. We just need to know how to work around the rule when we want certain kinds of behavior.</p><p>The trick to getting the pair to split in the second example is to introduce an additional div. The large square in the original example serves double duty-it’s both the thing that gets moved on hover and the thing that places a square under the bar. So we just need to restructure our HTML so that the parent div is only responsible for the movement, and contains two children that each render one of the squares. Once the squares are siblings they’re part of a broader stacking context that includes the bar, allowing their z-index values to have the intended effect.</p><h3>When to Use Positioned Elements</h3><p>These positioning options give you a lot of freedom, but most layouts should still mainly consist of static elements. The unnecessary use of positioned elements can lead to longer CSS files, more brittle code, and less predictable styling. Positioned elements can have a positive, powerful effect when used in targeted ways, but the layout of a page as a whole should nearly always be built with static elements arranged through a system like Flexbox or Grid.</p><p>That being said, let’s look at some cases where it <em>does</em> make sense to deviate from static positioning. I’ll go over some of the common use cases that I keep coming back to, but this certainly isn’t an exhaustive list. If you have your own favorite uses, let me know!</p><h4>Make Important Elements More Prominent</h4><p>This is a pretty broad category, but the basic idea is that if you have especially important information, buttons, or forms, you can make them more obvious and easier to access if you move them out of the normal flow of the document.</p><p>As an example, let’s look at a slightly more advanced version of a fixed header. In this case, you have a table of data with column names and a search bar at the top. Ideally, the names and search bar will be visible to the user whenever they see the table. But since the table might not always be on the screen, you can’t just give it a fixed position. Instead, you can use sticky positioning:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcodepen.io%2Fiangrubb%2Fembed%2Fpreview%2FpoyzmWw%3Fheight%3D600%26slug-hash%3DpoyzmWw%26default-tabs%3Djs%2Cresult%26host%3Dhttps%3A%2F%2Fcodepen.io&amp;display_name=CodePen&amp;url=https%3A%2F%2Fcodepen.io%2Fiangrubb%2Fpen%2FpoyzmWw&amp;image=https%3A%2F%2Fassets.codepen.io%2F4260516%2Finternal%2Fscreenshots%2Fpens%2FpoyzmWw.default.png%3Ffit%3Dcover%26amp%3Bformat%3Dauto%26amp%3Bha%3Dfalse%26amp%3Bheight%3D360%26amp%3Bquality%3D75%26amp%3Bv%3D2%26amp%3Bversion%3D1596569095%26amp%3Bwidth%3D640&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=codepen" width="800" height="600" frameborder="0" scrolling="no"><a href="https://medium.com/media/e09af9ff91a09d6a2bfadfda38a64353/href">https://medium.com/media/e09af9ff91a09d6a2bfadfda38a64353/href</a></iframe><p>To get this to work, I had to use multiple sticky elements. This was necessary in order to write the table using the semantically appropriate HTML tags. The sticky property wasn’t working on any of the table row elements, so I had to apply it to each table header element. Also, since the title and search bar can’t be in the table itself, they have to be in a separate div tag that’s also sticky. Everything behaves like a single sticky element because I applied coordinating heights and top values.</p><h4>Arrange Irregular Shapes</h4><p>Layout tools like Flexbox and Grid assume that your elements are rectangles. That’s typically an accurate assumption, but not always. When you work with non-rectangular shapes, static positioning sometimes results in the wrong distribution of white space between elements. In that case it can make sense to use positioned elements to create a more aesthetically satisfying layout.</p><p>Here’s a simple example involving some buttons meant to emulate a video game controller. The buttons have a wedge created with a clip-path, so I used absolute positioning to fit them together compactly:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcodepen.io%2Fiangrubb%2Fembed%2Fpreview%2FgOrOaoR%3Fheight%3D600%26slug-hash%3DgOrOaoR%26default-tabs%3Dcss%2Cresult%26host%3Dhttps%3A%2F%2Fcodepen.io&amp;display_name=CodePen&amp;url=https%3A%2F%2Fcodepen.io%2Fiangrubb%2Fpen%2FgOrOaoR&amp;image=https%3A%2F%2Fassets.codepen.io%2F4260516%2Finternal%2Fscreenshots%2Fpens%2FgOrOaoR.default.png%3Ffit%3Dcover%26amp%3Bformat%3Dauto%26amp%3Bha%3Dfalse%26amp%3Bheight%3D360%26amp%3Bquality%3D75%26amp%3Bv%3D2%26amp%3Bversion%3D1598881288%26amp%3Bwidth%3D640&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=codepen" width="800" height="600" frameborder="0" scrolling="no"><a href="https://medium.com/media/e525aed34cdbbdbfbfb7fd4213686594/href">https://medium.com/media/e525aed34cdbbdbfbfb7fd4213686594/href</a></iframe><p>I used a rotation to get each button in the right spot. I started by placing the left button, and then placed the rest of the elements by rotating them from that starting point. This works because I’ve set the set the buttons to transform relative to middle of their right side. You <em>could</em> position the buttons without a rotation, but placing elements radially simplifies the calculations.</p><h4>Stack Groups of Elements</h4><p>In some cases it makes sense to stack groups of elements on top of each other. Stacking elements results in a more compact layout, saving valuable space on the screen. It can also lead to more visually engaging content, as long as the technique is used on the right kinds of elements and in moderation.</p><p>The difficulty with stacking elements is ensuring that the hidden content is always accessible to the user. In some cases you can do this with pure CSS-as long as some portion of each element is revealed, it might be enough to set up a transition that reveals each element on hover. In the remaining cases you’ll need to use JavaScript to give the user the ability to rearrange elements.</p><p>Here’s an example involving a stack of numbered cards. I’m using JavaScript so that the user can click a button to move the top card to the back of the stack. On click, a CSS animation gets applied to the top card, moving it out and then behind the rest of the cards:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcodepen.io%2Fiangrubb%2Fembed%2Fpreview%2FwvGvrpM%3Fheight%3D600%26slug-hash%3DwvGvrpM%26default-tabs%3Djs%2Cresult%26host%3Dhttps%3A%2F%2Fcodepen.io&amp;display_name=CodePen&amp;url=https%3A%2F%2Fcodepen.io%2Fiangrubb%2Fpen%2FwvGvrpM&amp;image=https%3A%2F%2Fassets.codepen.io%2F4260516%2Finternal%2Fscreenshots%2Fpens%2FwvGvrpM.default.png%3Ffit%3Dcover%26amp%3Bformat%3Dauto%26amp%3Bha%3Dtrue%26amp%3Bheight%3D360%26amp%3Bquality%3D75%26amp%3Bv%3D2%26amp%3Bversion%3D1596826582%26amp%3Bwidth%3D640&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=codepen" width="800" height="600" frameborder="0" scrolling="no"><a href="https://medium.com/media/2b4137b880e9bca1eee8adec6c8fcf03/href">https://medium.com/media/2b4137b880e9bca1eee8adec6c8fcf03/href</a></iframe><p>The cards have position absolute and are placed in a container that has position relative. They’re rendered through JS and are assigned bottom, left, and z-index values based on their distance from the bottom of the stack. This is how the stack shifts slightly up and to the right. I applied a very slight box-shadow on each of the cards to add to this effect.</p><p>The animation I’m using is defined in the CSS file but applied in the JS file. Using CSS transitions is often sufficient for most basic animations, but in this case I had to use keframes to get the top card to shift out and then back. Note that I’m giving the animation an animation-fill-mode of forwards, so that it retains the CSS applied by the last frame. Also, I’m applying a transitioned change in bottom, left, and z-index values on the other cards, so they all slide slightly up while the top card shifts to the back.</p><h4>Apply a Partially Transparent Overlay</h4><p>Sometimes the easiest way to achieve a desired aesthetic through CSS is to build it up using multiple overlapping layers. This could involve stacking elements with fully transparent portions or perhaps even stacking partially transparent, colored elements that uniformly tint whatever is under them.</p><p>In this example, I used a partially transparent overly to make a simple monitor with animated scan lines that partially cover anything on the monitor screen:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcodepen.io%2Fiangrubb%2Fembed%2Fpreview%2FExKxLgK%3Fheight%3D600%26slug-hash%3DExKxLgK%26default-tabs%3Dcss%2Cresult%26host%3Dhttps%3A%2F%2Fcodepen.io&amp;display_name=CodePen&amp;url=https%3A%2F%2Fcodepen.io%2Fiangrubb%2Fpen%2FExKxLgK&amp;image=https%3A%2F%2Fassets.codepen.io%2F4260516%2Finternal%2Fscreenshots%2Fpens%2FExKxLgK.default.png%3Ffit%3Dcover%26amp%3Bformat%3Dauto%26amp%3Bha%3Dtrue%26amp%3Bheight%3D360%26amp%3Bquality%3D75%26amp%3Bv%3D2%26amp%3Bversion%3D1596648426%26amp%3Bwidth%3D640&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=codepen" width="800" height="600" frameborder="0" scrolling="no"><a href="https://medium.com/media/658db6debe510298878df64d5420f30f/href">https://medium.com/media/658db6debe510298878df64d5420f30f/href</a></iframe><p>The overlay is a repeating linear gradient, which makes some fully transparent regions and some slightly opaque regions. To animate the overlay, I wrapped it in another div that covers the monitor screen and hides any overflowing content. The overlay itself is twice as tall as the monitor and is animated to move up gradually and loop back around when its bottom reaches the bottom of the overlay wrapper. The wrapper div and the div for the monitor’s contents are placed in the same stack through absolute positioning and setting their z-index values.</p><p>This provides a nice example of how stacking contexts can be a benefit, rather than an annoyance. I <em>never</em> want the contents of the monitor to show up on top of the scan lines. However, I <em>may</em> want to use different z-index values within the monitor to control overlap. You might worry that if try placing something on top of the green square, I could accidentally use a z-index that pops it out above the scan lines. Fortunately, that’s not a concern in this case, since the z-index value on the monitor contents div creates a new stacking context. That allows me to freely assign whatever z-index values I want to elements on the monitor and know that they’ll always end up below the scan lines.</p><h4>Add Tool Tips on Hover</h4><p>Another great use for positioned elements is temporarily showing the user information without breaking the normal flow of the document. When user behavior triggers things like modal windows, error and alert messages, and tool tips, you don’t want them to push around the rest of your content. Instead, you can position them on top of your content and allow the user to dismiss them when that content needs to be accessed.</p><p>In this example, I use absolute positioning to display a tool tip on hover:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcodepen.io%2Fiangrubb%2Fembed%2Fpreview%2FxxVxJKM%3Fheight%3D600%26slug-hash%3DxxVxJKM%26default-tabs%3Dcss%2Cresult%26host%3Dhttps%3A%2F%2Fcodepen.io&amp;display_name=CodePen&amp;url=https%3A%2F%2Fcodepen.io%2Fiangrubb%2Fpen%2FxxVxJKM&amp;image=https%3A%2F%2Fassets.codepen.io%2F4260516%2Finternal%2Fscreenshots%2Fpens%2FxxVxJKM.default.png%3Ffit%3Dcover%26amp%3Bformat%3Dauto%26amp%3Bha%3Dfalse%26amp%3Bheight%3D360%26amp%3Bquality%3D75%26amp%3Bv%3D2%26amp%3Bversion%3D1596850748%26amp%3Bwidth%3D640&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=codepen" width="800" height="600" frameborder="0" scrolling="no"><a href="https://medium.com/media/1db1baa6377af72671bbddc76b331c20/href">https://medium.com/media/1db1baa6377af72671bbddc76b331c20/href</a></iframe><p>Since tool tips can be used for many kinds of elements, I designed the CSS to be versatile-to use it, you just have to apply the tip-able class to the element you want to have the tool tip, then put the tip’s content in a span with the class tool-tip. I use the before and after pseudo-elements to minimize the need to write out any extra HTML.</p><p>You might notice that I’ve put a thin transparent rectangle into the element using .tool-tip::before. The point of this element is to help make the hover work right. The tool tip should display as long as the user hovers over the base element or the tool tip itself. However, I also wanted a small margin between the tip and the base element. Implementing this directly as a margin means that if the user moves their cursor from the base element to the tool tip, it stops existing before they can get to the tool tip. The transparent rectangle acts like a margin but also bridges the base element and the tool tip.</p><p>The animation is just a matter of transitioning between scales of 1 or 0. It doesn’t look quite right by default, but the animation feels much more natural with the transform-origin changed to start from the bottom center of the element.</p><h4>Locate Markers on a Map or Image</h4><p>Overlapping content can help visualize certain kinds of data. You might have images with annotations that target specific coordinates on the image or maps with pointers that target specific locations on the map. Using absolute positioning, you can visually display your coordinate data.</p><p>Here’s a demo that takes graph data and uses it to display a map and a character that can move around the map (click a node to move the character to that node):</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcodepen.io%2Fiangrubb%2Fembed%2Fpreview%2FYzqzjOG%3Fheight%3D600%26slug-hash%3DYzqzjOG%26default-tabs%3Djs%2Cresult%26host%3Dhttps%3A%2F%2Fcodepen.io&amp;display_name=CodePen&amp;url=https%3A%2F%2Fcodepen.io%2Fiangrubb%2Fpen%2FYzqzjOG&amp;image=https%3A%2F%2Fassets.codepen.io%2F4260516%2Finternal%2Fscreenshots%2Fpens%2FYzqzjOG.default.png%3Ffit%3Dcover%26amp%3Bformat%3Dauto%26amp%3Bha%3Dfalse%26amp%3Bheight%3D360%26amp%3Bquality%3D75%26amp%3Bv%3D2%26amp%3Bversion%3D1596719994%26amp%3Bwidth%3D640&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=codepen" width="800" height="600" frameborder="0" scrolling="no"><a href="https://medium.com/media/f4689775cb5b1f3d27ed7309a9c7e1cc/href">https://medium.com/media/f4689775cb5b1f3d27ed7309a9c7e1cc/href</a></iframe><p>My node data has x and y coordinates built in, and I use these to display the nodes at the correct spots on the map. I’m using percentages as units for the top and left properties, which makes it easier to responsively resize the map. To render an edge between two nodes, I start by placing it coming out of the right side of one of the nodes it connects. I do a bit of math to calculate its length and angle to the second node, and I then use these values to set the width of the edge element and rotate it enough so that it connects.</p><h4>Implement a Fixed Aspect Ratio</h4><p>Setting the width and height of an element using percentages is a simple way to make your elements more responsive. This approach works well most of the time, but has a significant limitation-it doesn’t allow the responsive element to have a fixed aspect ratio. What you sometimes need is an element that’s responsive to the width of its parent, but has a height that scales in some proportion with its width. There’s a pattern that implements this behavior, and it requires the use of positioned elements. Here’s a basic setup (hover to change the width of the rectangle):</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcodepen.io%2Fiangrubb%2Fembed%2Fpreview%2FOJNPPWE%3Fheight%3D600%26slug-hash%3DOJNPPWE%26default-tabs%3Dcss%2Cresult%26host%3Dhttps%3A%2F%2Fcodepen.io&amp;display_name=CodePen&amp;url=https%3A%2F%2Fcodepen.io%2Fiangrubb%2Fpen%2FOJNPPWE&amp;image=https%3A%2F%2Fassets.codepen.io%2F4260516%2Finternal%2Fscreenshots%2Fpens%2FOJNPPWE.default.png%3Ffit%3Dcover%26amp%3Bformat%3Dauto%26amp%3Bha%3Dfalse%26amp%3Bheight%3D360%26amp%3Bquality%3D75%26amp%3Bv%3D2%26amp%3Bversion%3D1598407839%26amp%3Bwidth%3D640&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=codepen" width="800" height="600" frameborder="0" scrolling="no"><a href="https://medium.com/media/8347c1d1ce3925d615fd26cd81ae1612/href">https://medium.com/media/8347c1d1ce3925d615fd26cd81ae1612/href</a></iframe><p>The key to making this work is a peculiar property of padding-any vertical padding defined in percentages is based on the percentage of the parent element’s width. This means that if we give an element a padding-top value of 100% and give in no height, the overall height of the element (including the padding) will be the same as the width of its parent. The child can also be given a width of 100%, making it a perfect square. If we want a different aspect ratio, we can just use calc to set the required amount of padding (in the example, I’ve set the rectangle to be five times as wide as it is tall).</p><p>If you just used two elements and you put content inside the child, its height will increase beyond 0 and ruin the effect. The solution is to make yet another child element that has both height and the same overall dimensions as its parent. You can do this with absolute positioning, having the top, bottom, left, and right values of the child all set to 0 so it covers the entirety of its parent. So the solution ultimately involves nesting three elements. You adjust the width of the whole by adjusting the width of the outermost element, you adjust the aspect ratio by adjusting the padding-top of the middle element, and you add internal content by putting it inside the innermost element.</p><p><em>Originally published at </em><a href="https://www.iangrubb.com/blog/a-guide-to-css-position"><em>https://www.iangrubb.com</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f5323b154bd4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Make Out of This World Recursive Components in React]]></title>
            <link>https://medium.com/@ian_grubb/how-to-make-out-of-this-world-recursive-components-in-react-85039ca6e967?source=rss-47e6201de8e0------2</link>
            <guid isPermaLink="false">https://medium.com/p/85039ca6e967</guid>
            <category><![CDATA[react]]></category>
            <dc:creator><![CDATA[Ian Grubb]]></dc:creator>
            <pubDate>Thu, 12 Sep 2019 16:55:57 GMT</pubDate>
            <atom:updated>2019-09-12T16:55:57.800Z</atom:updated>
            <content:encoded><![CDATA[<p>One of the big advantages of React is that it lets you make complex components out of other React components. For instance, you might make a Form component that contains a SubmitButton component and multiple TextInput components. You can even build components recursively, where a component of a certain kind contains more instances of that same kind of component. This is a powerful technique that can be used to create components that exhibit some pretty cool behavior.</p><p>To demonstrate how this works, I’ll walk through the process of making an Orbiter component, which will allow us to animate circles so that they orbit other circles. It’s a recursive component because an orbiting circle can itself have other circles that orbit it. As a result, the path of a circle depends not just on its own orbit, but also the orbit of the object it orbits, the orbit of the object that that object orbits, and so on.</p><p>To start, let’s just make a fixed circle at the center of the screen. I’ll handle styling with the <a href="https://www.styled-components.com/">Styled Components</a> library, which lets us to write CSS in JS. Check out the App component file to see how this works:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*a9Uf0bTz0gYqI6A0U05RzQ.png" /><figcaption>The App Component File</figcaption></figure><p>Eventually we’ll render a Sun component and Orbiter components based on the orbiterData array. That array is currently empty, so for now we’re just rendering a Sun with a radius of 40px. Sun is a styled component, with its CSS defined at the top of the file. We’re passing the prop radius to help determine how the Sun we’re rendering should be styled (specifically, how tall and wide it should be and where on the screen it should be rendered). This code gives us:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8lGFzPMHMtpbEOkEt5TqIg.png" /><figcaption>The Sun</figcaption></figure><p>Not much to look at so far, so let’s add those Orbiters! To render an Orbiter, we need to know a few things about it: its radius, the distance from the object it orbits, how fast it orbits, what angle it starts orbiting at, its color, and what orbiters orbit it. We’ll eventually get all of this from orbiterData array. Whenever we render an Orbiter, we’ll use some of that data to style the orbiting Circle itself, and then we’ll recursively render all of the Orbiters that orbit that Orbiter. Here’s the code that manages that:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cvFrFTFKSEVQEUSk3Of3rg.png" /><figcaption>Orbit Component Render</figcaption></figure><p>Next up, we need to define the styling of the Circle component. Again, we’ll do this by making a styled component. This time, it will even let us define CSS animations! Here’s the styling:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gJGh_NqshKdKOKcBHNn-NQ.png" /><figcaption>Circle Styling and Animation</figcaption></figure><p>With all of that in place, all we need is data that we can use to render Orbiters. So let’s go back and add some data to orbiterData. First, a single orbiter:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/590/1*j9hEgeToRtxfRO4_CecoVQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*P2xdKgS5CP4UZoEdkylnYQ.gif" /></figure><p>Good so far, but the point was to render components recursively. To do that, we just need to keep adding more data to the orbiters key of each orbiter. Here’s an example with three orbiters in a single chain:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/710/1*yD7fzc_5NToLuYPvOY6O_g.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*ttNCkGB2CZrZ2h-I3qYRYw.gif" /></figure><p>At this point, we can make some pretty complex animations, as long as we have a source of well-structured data. As one final example, here’s what we get with some partially randomized data, meant to simulate planets with moons and an asteroid belt:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*320MnHis-PUEn6tnoOd5OQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*oVKvw2BGQwjrBtQTq6sCXQ.gif" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=85039ca6e967" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Use the Y Combinator in JavaScript]]></title>
            <link>https://medium.com/@ian_grubb/how-to-use-the-y-combinator-in-javascript-76b8616bb7a2?source=rss-47e6201de8e0------2</link>
            <guid isPermaLink="false">https://medium.com/p/76b8616bb7a2</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[recursion]]></category>
            <category><![CDATA[functional-programming]]></category>
            <dc:creator><![CDATA[Ian Grubb]]></dc:creator>
            <pubDate>Wed, 21 Aug 2019 13:01:52 GMT</pubDate>
            <atom:updated>2020-09-12T18:15:42.817Z</atom:updated>
            <content:encoded><![CDATA[<p>Contemporary programming languages allow various ways of repeatedly calling a function. For instance, some options in JavaScript include:</p><ol><li>Iterating with a for or while loop.</li><li>Iterating with forEach on an array.</li><li>Recursively calling a named function from within itself.</li></ol><p>But imagine a world where ECMA suddenly removes for, while, forEach, and named functions from Javascript. In that world, could we still perform all of the computations that are currently possible?</p><p>It turns out we could! As long as JavaScript allows first-class functions (functions that can take other functions as arguments) we’ll be able to write all of the same recursive computations. This is possible because of the <strong>Y Combinator</strong>, a function that comes from the Lambda Calculus. There, it’s written:</p><pre>λf.(λx.f(x x))(λx.f(x x))</pre><p>But I’m not here to talk about the Lambda Calculus. How does this work in JS?</p><h3>An Engine for Recursion</h3><p>A recursive computation tells a computer to call some function indefinitely, until some condition is met. But how do we get a process to go on indefinitely?</p><p>The first step is to define the <strong>M Combinator</strong>. The M Combinator is a function that takes a callback function and returns that function applied to itself:</p><pre>const M = cb =&gt; cb(cb)</pre><p>That’s a bit hard to think about, in part because it doesn’t really make sense for many callback functions. If we call M on a function that adds 2 to a number, what would it mean to call that function on itself? You can’t add 2 to a function!</p><pre>const addTwo = num =&gt; num + 2</pre><pre>addTwo(3) <br>  // returns 5<br>M(addTwo)<br>  // doesn&#39;t really make sense</pre><p>But M can make sense, as long as it’s called on a function that itself takes functions as arguments. For instance, calling M on a function that takes a function and applies it twice <em>does</em> make sense. It returns a function that takes a function and calls it four times.</p><pre>const callTwice = cb =&gt; x =&gt; cb(cb(x))</pre><pre>callTwice(addTwo)(3)<br>  // returns 7</pre><pre>M(callTwice)(addTwo)(3)<br>  // returns 11<br>  // M(callTwice) takes a function and calls it four times.</pre><p>With M, we can easily define a computation that runs indefinitely. We just apply M to itself!</p><pre>const Ω = M(M)</pre><pre>  // aka (cb =&gt; cb(cb))(cb =&gt; cb(cb))</pre><p>The resulting expression — the <strong>Ω combinator </strong>— returns <em>itself</em>. Obviously we don’t want to use that expression on its own, since it causes an error. But if we could harness the power of Ω<strong> </strong>safely, it could give us the ability to perform recursive computations.</p><h3>The Structure of a Recursive Step</h3><p>Recursion involves calling a function repeatedly. For our purposes, that function has to have a special structure. Suppose we have some array and we want to console.log each of its elements. Normally, we might use the function logStep:</p><pre>const logStep = (array, index = 0) =&gt; {<br>  if (index &lt; array.length) {<br>    console.log(array[index])<br>    logStep(array, index + 1)<br>  }<br>}</pre><p>In order to use the Y combinator, we need to rewrite logStep in <strong>continuation passing style</strong>. All this means is that we need to give logStep a way to plan for the future. We do this by having it take an additional argument (a continuation), which is a callback function to be applied after the main work of logStep is finished:</p><pre>const logStepCPS = continuation =&gt; (array, index = 0) =&gt; {<br>  if (index &lt; array.length) {<br>    console.log(array[index])<br>    continuation(array, index + 1)<br>  }<br>}</pre><p>Now we can tell logStepCPS what we intend to do in our program after the function logs an element, and we give the function the responsibility of making sure the program continues in that way.</p><h3>Putting it All Together</h3><p>With all of that in place, all we need is a continuation that means “do that again”. If we had that, we could pass it to logStepCPS in order to recursively log the elements of array.</p><p>Enter the Y combinator. The Y has a similar structure to Ω, except that Y leaves room for a step function like logStepCPS:</p><pre>const Ω =      (cb =&gt;   cb(cb)) (cb =&gt;   cb(cb))</pre><pre>const Y = s =&gt; (cb =&gt; s(cb(cb)))(cb =&gt; s(cb(cb)))</pre><p>What’s crucial about Y is that the expression Y(logStepCPS) returns logStepCPS(Y(logStepCPS)). We defined logStepCP to take a continuation, and Y(logStepCPS) <em>is </em>that continuation. The intended result is an oscillating pattern where:</p><ol><li>Evaluating Y(logStepCPS) prompts a new logStepCPS call.</li><li>That call consumes Y(logStepCPS) as one of its arguments.</li><li>That call eventually returns Y(logStepCPS), restarting the process.</li></ol><p>As a byproduct, the index should continue to grow and new elements of the array should be logged:</p><pre>(Y (logStepCPS))(array, index)<br>logStepCPS (Y (logStepCPS))(array, index)<br>   // array[index] gets logged<br>(Y (logStepCPS))(array, index + 1)<br>logStepCPS (Y (logStepCPS))(array, index + 1)<br>  // array[index + 1] gets logged<br>(Y (logStepCPS))(array, index + 2)<br>logStepCPS (Y (logStepCPS))(array, index + 2)<br>  // array[index + 2] gets logged<br>  // etc</pre><p>This continues until the index argument is equal to array.length, at which point logStepCPS doesn’t call the continuation.</p><p>Notice that although I’ve used the constantsY and logStepCPS for convenience, they weren’t required by the process — we <em>could</em> have written them out in full detail. That means we have what we set out for: a method for recursion that only relies on anonymous higher-order functions. We did it, we’re done!</p><h3><strong>One More Thing…</strong></h3><p>Or we would be, if we were in the Lambda Calculus. Unfortunately, JavaScript uses different rules for evaluating expressions, which makes our life a bit harder. Specifically, JavaScript uses <strong>eager</strong> evaluation, while the Lambda Calculus uses <strong>lazy</strong> evaluation. This means that in JS, the actual result of calling Y (logStepCPS)(input) is:</p><pre>(Y (logStepCPS))(input)       <br>logStepCPS (Y (logStepCPS))(input)<br>logStepCPS (logStepCPS (Y (logStepCPS)))(input)<br>// goes forever</pre><p>So Y breaks our program, just like Ω.</p><p>Fortunately, there’s a simple fix. All we have to do is<strong> thunk</strong> some of the expressions in Y, which delays the evaluation of (Y (logStepCPS)) in a manner that simulates lazy evaluation. Thunking is just taking an expression and replacing it with a function that takes no arguments and returns the expression when called. The means we’ll also have to change our step function. Here’s the result:</p><pre>  // Good:<br>const Y = s =&gt; (cb =&gt; s(() =&gt; cb(cb)))(cb =&gt; s(() =&gt; cb(cb)))</pre><pre>  // Bad:<br>const Y = s =&gt; (cb =&gt; s(      cb(cb)))(cb =&gt; s(      cb(cb)))</pre><pre>  // Good:<br>const logStepCPS = continuation =&gt; (array, index = 0) =&gt; {<br>  if (index &lt; array.length) {<br>    console.log(array[index])<br>    continuation()(array, index + 1)<br>  }<br>}</pre><pre>// Bad:<br>const logStepCPS = continuation =&gt; (array, index = 0) =&gt; {<br>  if (index &lt; array.length) {<br>    console.log(array[index])<br>    continuation(array, index + 1)<br>  }<br>}</pre><p>Ok, <em>now</em> we’re done!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=76b8616bb7a2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Elegant Iteration in Ruby]]></title>
            <link>https://medium.com/@ian_grubb/elegant-iteration-in-ruby-7d016253e5b1?source=rss-47e6201de8e0------2</link>
            <guid isPermaLink="false">https://medium.com/p/7d016253e5b1</guid>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Ian Grubb]]></dc:creator>
            <pubDate>Fri, 26 Jul 2019 21:03:58 GMT</pubDate>
            <atom:updated>2019-07-26T21:03:58.481Z</atom:updated>
            <content:encoded><![CDATA[<p>Ruby’s each is a powerful, general-purpose method for iterating over arrays. At least in theory, anything you want to do with the elements of an array can be done with each. This can make it tempting to ignore the other, more special-purpose iteration methods that Ruby has to offer. Why bother memorizing more syntax when each alone can suffice?</p><p>The answer is simple: using special-purpose iteration methods makes your code better. Using these methods helps you code more quickly, leaving you with more time to write the code that matters. Remembering these methods also makes it easier to remember the different kinds of things you can do with arrays, helping you to be more imaginative in how you approach coding problems. And above all, using these methods helps make your code more concise, readable, and elegant.</p><p>Here’s an example of what I have in mind. Imagine we’re writing a method that takes an array and returns the even numbers from that array. We <em>could</em> do this using each:</p><pre>def select_evens(initial_values)<br>    selected_values = []<br>    initial_values.each do |value|<br>        if value.even?<br>            selected_values &lt;&lt; value<br>        end<br>    end<br>    selected_values<br>end</pre><p>This code is fine. It at least returns the right values, but it could still be better. Rather than code the whole process of selecting the evens, we can just tell Ruby that we want the selection of evens:</p><pre>def select_evens(initial_values)<br>    initial_values.select {|value| value.even?}<br>end</pre><p>Notice all of the ways this helps to shorten the code. We no longer have to declare and return the selected_values variable, saving two lines. We also don’t need to explicitly shovel even values into selected_values or end our conditional, which saves another two lines. And shortening the block means we can fit it comfortably inside curly braces, saving another two lines.</p><p>Let’s try a more complex example. Imagine we have an array of people, each with an age and a name. We want to sort them by age, starting with the oldest. But if two people have the same age, they should be sorted alphabetically. Here’s one way to do this with each:</p><pre>def sort_by_age_then_name(people)<br>    sorted_array = [people.pop]<br>    people.each do |person|<br>        n = 0<br>        sorted_array.each do |sorted_person|<br>            if (person.age &gt; sorted_person.age) || <br>               (person.age == sorted_person.age &amp;&amp;<br>                person.name &lt; sorted_person.name)<br>                sorted_array.insert(n, person)<br>                break<br>            elsif n == sorted_array.length - 1<br>                sorted_array &lt;&lt; person<br>            else<br>                n += 1<br>            end<br>        end<br>    end<br>    sorted_array<br>end</pre><p>This gets the job done, but it’s ugly. Here’s a more elegant solution:</p><pre>def sort_by_age_then_name(people)<br>   people.sort_by{|person| [-person.age, person.name]}<br>end</pre><p>This time we’re using sort_by, which lets you tell Ruby how to sort an array. You supply a block that returns a value for each array element and sort_by orders the elements based on the order of the values they produce. Common use cases involve numerical or alphabetical orderings. Another possibility (used in this example), involves sorting based on returned arrays. Determining the order of two arrays involves comparing the order of their first elements, the order of their second elements if the first elements are the same, and so on. That’s how the code above first sorts by age, and then alphabetically by name when people have the same age.</p><p>Maybe the hardest part about using special-purpose iteration methods is remembering the right tool for the job in the moment. Using methods like select and sort_by isn’t so difficult when you remember that they exist, but that requires training yourself to notice when a situation might require them. And you won’t know what those situations are unless you have a guide to what the relevant methods are in the first place.</p><p>Unfortunately, the Ruby documentation isn’t much help here. It’s great if you know what method you want more information about, but a long, alphabetical list of methods isn’t so useful when you don’t quite know what you’re looking for. What’s needed is a moderately selective list of potentially useful methods, sorted by the kinds of tasks they’re used for.</p><p>So I decided to make my own version that kind of list. I went through the Ruby documentation on Array and Enumerator methods and tried my best to put it into a more useable order. The full list of methods would have been too long, so I had to make a lot of judgment calls about what methods are useful enough to include. I also had to make judgment calls about what categories to use in sorting the useful methods. In other words, this is an idiosyncratic list. Having it has helped me use special-purpose methods more often in my code, and it may help you too. But whether or not it helps, I highly encourage you to make your own such list, since it’s a great way to learn about these methods.</p><p>I’ll put the organized list of methods below, followed by a more detailed list with brief descriptions of the methods and simple examples of them in use. Please note: this <em>is not </em>a replacement for the full documentation. I try to say just enough about the methods to make it easy to remember what they do in general. But I don’t say enough to cover all of the ways they can be used or potential bugs that might arise in using them. So think of this as a point and be ready to look up more detailed documentation as desired.</p><p><em>Happy iterating!</em></p><h4><strong>Get a Special Result from Iterating</strong></h4><ul><li>Construct a new array of the same size: map / collect</li><li>Construct a new, possibly larger array: flat_map</li><li>Use array elements as arguments for a method: inject / reduce , each_with_object</li></ul><h4><strong>Control the Manner of Iteration</strong></h4><ul><li>Iterate over portions of an array: each_cons , each_slice</li><li>Iterate multiple times: cycle</li><li>Iterate with an explicit index: with_index</li></ul><h4><strong>Select a Portion of an Array</strong></h4><ul><li>Select a portion based on a condition: select , reject</li><li>Select a portion based on order: drop_while , take_while</li></ul><h4><strong>Choose an Element of an Array</strong></h4><ul><li>Find an element satisfying a condition: find / detect</li><li>Find an element based on a comparison: max_by , min_by</li></ul><h4><strong>Query the Elements of an Array</strong></h4><ul><li>Check how many satisfy a condition: none? , all? , any? , one? , count</li><li>Distinguish elements based on a return value: partition , group_by</li></ul><h4><strong>Sort Elements of an Array</strong></h4><ul><li>Sort based on current order: reverse , rotate</li><li>Sort based on a condition: sort_by</li></ul><h4><strong>Work with Nested Arrays</strong></h4><ul><li>Make a nested array from portions of an array: combination , permutation , repeated_combination , repeated_permutation</li><li>Make a nested array from two arrays: product , zip</li></ul><h3>Get a Special Result from Iterating</h3><p><strong>Construct a new array of the same size</strong></p><p>map / collect collect the return values from a block and return an array of those values.</p><pre>initial_array = [1, 2, 3]<br>initial_array.collect{|number| number + 1}<br># =&gt; [2, 3, 4]</pre><p><strong>Construct a new, possibly larger array</strong></p><p>flat_map collects arrays returned from a block and puts their elements into an array.</p><pre>initial_array = [1, 2, 3]<br>initial_array.flat_map{|number| [number, -number]}<br># =&gt; [1, -1, 2, -2, 3, -3]</pre><p><strong>Use array elements as arguments for a method</strong></p><p>inject / reduce are used with a block containing a function that takes two values (in the example below, total and element). At each stage in the iteration, the previous total is called with the next element, giving the next stage’s total. The final total is returned.</p><p>When called with an argument (initial_value), the first total is initial_value. When called with no argument, the first total is the first element of the array.</p><pre>initial_array = [1, 2, 3, 4]<br>initial_array.inject(0) {|total, element| total + element}<br># Does: 0 + 1 = 1<br>#       1 + 2 = 3<br>#       3 + 3 = 6<br>#       6 + 4 = 10<br>#       =&gt; 10</pre><p>each_with_objectis called with an initial_object and used with a block containing a function that takes two values (objectand element). At each stage in the iteration, the previous object is changed based on that stage’s element, giving the next stage’s object. The final object is returned.</p><pre>initial_array = [1, 2, 3, 4]<br>initial_object = {}<br>initial_array.each_with_object(initial_object) do |element, object| <br>  object[element.to_s] = element<br>end<br># =&gt; {&quot;1&quot;=&gt;1, &quot;2&quot;=&gt;2, &quot;3&quot;=&gt;3, &quot;4&quot;=&gt;4}</pre><p>Note the position of element in the blocks above: it comes second in inject / reduce, but first in each_with_object.</p><h3><strong>Control the Manner of Iteration</strong></h3><p><strong>Iterate over portions of an array</strong></p><p>each_cons takes an integer argument i and iterates over all consecutive sub-divisions of the array with length i.</p><pre>initial_array = [1, 2, 3, 4, 5]<br>initial_array.each_cons(3) do |contained_array|<br>  print contained_array<br>end<br># [1, 2, 3][2, 3, 4][3, 4, 5]</pre><p>each_slice takes an integer argument i and iterates over the consecutive sub-divisions that slice the original array into arrays with length i. Any remainder elements get put into an array with length less that i.</p><pre>initial_array = [1, 2, 3, 4, 5, 6, 7]<br>initial_array.each_slice(3) do |contained_array|<br>  print contained_array<br>end<br># [1, 2, 3][4, 5, 6][7]</pre><p><strong>Iterate multiple times</strong></p><p>cycle iterates through an array multiple times. Call with an integer argument to cycle that many times. Call without an argument to cycle indefinitely.</p><pre>initial_array = [1, 2, 3]<br>initial_array.cycle(2){|number| print number}<br># 123123</pre><p><strong>Iterate with an explicit index</strong></p><p>with_index can be used with an enumerable to iterate with an index value.</p><pre>initial_array = [2, 1, 0, 3]<br>initial_array.collect.with_index{|element, index| index * element}<br># Does: 0 * 2 = 0<br>#       1 * 1 = 1<br>#       2 * 0 = 0<br>#       3 * 3 = 9<br>#       =&gt; [0, 1, 0, 9]</pre><h3><strong>Select a Portion of an Array</strong></h3><p><strong>Select a portion based on a condition</strong></p><p>select returns an array of the values for which the block returns true.</p><pre>initial_array = [1, 2, 3, 4]<br>initial_array.select{|integer| integer.even?}<br># =&gt; [2, 4]</pre><p>reject returns an array of the values for which the block returns false.</p><pre>initial_array = [1, 2, 3, 4]<br>initial_array.reject {|integer| integer.even?}<br># =&gt; [1, 3]</pre><p><strong>Select a portion based on order</strong></p><p>drop_while returns the original elements, excluding those before before the first index where the block returns false.</p><pre>initial_array = [1, 2, 3, -1, -2, -3]<br>initial_array.drop_while {|integer| integer &lt; 3}<br># =&gt; [3, -1, -2, -3]</pre><p>take_while returns the original elements, excluding those at or after the first index where the block returns false.</p><pre>initial_array = [1, 2, 3, -1, -2, -3]<br>initial_array.take_while {|integer| integer &lt; 3}<br># =&gt; [1, 2]</pre><h3><strong>Choose an Element of an Array</strong></h3><p><strong>Find an element satisfying a condition</strong></p><p>find / detect return the <em>first</em> value satisfying a condition, or nil if no value is found.</p><pre>array = [0, 1, 2, -1, -2]<br>array.find {|integer| integer &lt; 0 }<br># =&gt; -1</pre><p><strong>Find an element based on a comparison</strong></p><p>max_by returns the element that maximizes the return value of the block. If there is a tie, it returns the first such element. If an integer argument i is passed, it will return an array of the i largest elements instead.</p><pre>array = [&quot;a&quot;, &quot;few&quot;, &quot;test&quot;, &quot;strings&quot;]<br>array.max_by {|string| string.length}<br># =&gt; &quot;strings&quot;</pre><p>min_by returns the element that minimizes the return value of the block. If there is a tie, it returns the first such element. If an integer argument i is passed, it will return an array of the i smallest elements instead.</p><pre>array = [&quot;a&quot;, &quot;few&quot;, &quot;test&quot;, &quot;strings&quot;]<br>array.min_by {|string| string.length}<br># =&gt; &quot;a&quot;</pre><h3><strong>Query the Elements of an Array</strong></h3><p><strong>Check how many satisfy a condition</strong></p><p>none? returns true if none of the elements in the array make the block return true.</p><pre>array = [1, 2, 3, 4]<br>array.none? {|integer| integer.even?}<br># =&gt; false</pre><p>all? returns true if all of the elements in the array make the block return true.</p><pre>array = [1, 2, 3, 4]<br>array.all? {|integer| integer.even?}<br># =&gt; false</pre><p>any? returns true if at least one of the elements in the array make the block return true.</p><pre>array = [1, 2, 3, 4]<br>array.any? {|integer| integer.even?}<br># =&gt; true</pre><p>one? returns true if exactly one element in the array makes the block return true.</p><pre>array = [1, 2, 3, 4]<br>array.one? {|integer| integer.even?}<br># =&gt; false</pre><p>count returns the number of elements in the array that make the block return true.</p><pre>array = [1, 2, 3, 4]<br>array.count {|integer| integer.even?}<br># =&gt; 2</pre><p><strong>Distinguish elements based on a return value</strong></p><p>partition returns an array of two arrays. The first array contains the elements that make the block return true and the second contains the elements that make the block return false.</p><pre>initial_array = [1, 2, 3, 4]<br>initial_array.partition {|integer| integer.even?}<br># =&gt; [[2, 4], [1, 3]]</pre><p>group_by returns a hash. Its keys are the return values of a block. The value for each key is the array of elements that all return that key.</p><pre>array = [-2, -1, 0, 1, 2]<br>array.group_by {|integer| integer * integer}<br># =&gt; {4 =&gt; [-2, 2], 1 =&gt; [-1, 1], 0 =&gt; [0]}</pre><h3><strong>Sort Elements of an Array</strong></h3><p><strong>Sort based on current order</strong></p><p>reverse returns an array in reversed order.</p><pre>array = [1, 2, 3]<br>array.reverse<br># =&gt; [3, 2, 1]</pre><p>rotate takes an integer i as an argument. It moves the first element to the end of the array, and it does this i times. A negative value for i rotates in the opposite direction.</p><pre>array = [1, 2, 3, 4]<br>array.rotate(2)<br># =&gt; [3, 4, 1, 2]<br>array.rotate(-1)<br># =&gt; [4, 1, 2, 3]</pre><p><strong>Sort based on a condition</strong></p><p>sort_by uses a block to calculate a value for each element of the array, then sorts the elements of the array by comparing the resulting values. If two elements are tied, they maintain the same order as in the original array.</p><pre>array = [-2, -1, 0, 1, 2]<br>array.sort_by{|integer| integer * integer}<br># =&gt; [0, -1, 1, -2, 2]</pre><h3><strong>Work with Nested Arrays</strong></h3><p><strong>Make a nested array from portions of an array</strong></p><p>combination takes a non-negative integer i. It yields the length-i portions of an array, where each portion preserves order and doesn’t repeat elements.</p><pre>initial_array = [1, 2, 3]<br>initial_array.combination(2).to_a<br># =&gt; [[1, 2], [1, 3], [2, 3]]</pre><p>permutation takes a non-negative integer i. It yields the length-iportions of an array, where each portion needn’t preserve order and doesn’t repeat elements.</p><pre>initial_array = [1, 2, 3]<br>initial_array.permutation(2).to_a<br># =&gt; [[1, 2], [1, 3], [2, 1], [2, 3], [3, 1], [3, 2]]</pre><p>repeated_combination takes a non-negative integer i. It yields the length-iportions of an array, where each portion preserves order and may repeat elements.</p><pre>initial_array = [1, 2, 3]<br>initial_array.repeated_combination(2).to_a<br># =&gt; [[1, 1], [1, 2], [1, 3], [2, 2], [2, 3], [3, 3]]</pre><p>repeated_permutation takes a non-negative integer i. It yields the length-iportions of an array, where each portion needn’t preserve order and may repeat elements.</p><pre>initial_array = [1, 2, 3]<br>initial_array.repeated_permutation(2).to_a<br># =&gt; [[1, 1], [1, 2], [1, 3], [2, 1], [2, 2], [2, 3], [3, 1], [3, 2], [3, 3]]</pre><p><strong>Make a nested array from two arrays</strong></p><p>product is called on a first_array and takes a second_array as an argument. It returns an array of arrays, where each array is one possible combination of an element from first_array and an element from second_array.</p><pre>first_array = [1, 2, 3]<br>second_array = [&quot;a&quot;, &quot;b&quot;]<br>first_array.product(second_array)<br># =&gt; [[1, &quot;a&quot;], [1, &quot;b&quot;], [2, &quot;a&quot;], [2, &quot;b&quot;], [3, &quot;a&quot;], [3, &quot;b&quot;]]</pre><p>zip is called on a first_array and takes a second_array as an argument. It returns an array of arrays, where the elements of each array are those from first_array and second_array that share an index. If second_array has insufficient elements, nil is used instead. If second_array has excessive elements, they are ignored.</p><pre>first_array = [1, 2, 3]<br>second_array = [&quot;a&quot;, &quot;b&quot;]<br>first_array.zip(second_array)<br># =&gt; [[1, &quot;a&quot;], [2, &quot;b&quot;], [3, nil]]</pre><pre>first_array = [1, 2]<br>second_array = [&quot;a&quot;, &quot;b&quot;, &quot;c&quot;]<br>first_array.zip(second_array)<br># =&gt; [[1, &quot;a&quot;], [2, &quot;b&quot;]]</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7d016253e5b1" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>