<?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 Maxwell Russell on Medium]]></title>
        <description><![CDATA[Stories by Maxwell Russell on Medium]]></description>
        <link>https://medium.com/@MisteRussell?source=rss-5ec3f8b70c39------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*lged9_UnfThr-XvahWj-bw.jpeg</url>
            <title>Stories by Maxwell Russell on Medium</title>
            <link>https://medium.com/@MisteRussell?source=rss-5ec3f8b70c39------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 24 Nov 2026 07:51:38 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@MisteRussell/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[AWS AppSync + GraphQL + DynamoDB: Building Objects from a Single Table from Multiple Table Entries]]></title>
            <link>https://medium.com/@MisteRussell/aws-appsync-graphql-dynamodb-building-objects-from-a-single-table-from-multiple-table-entries-50e86d5ef503?source=rss-5ec3f8b70c39------2</link>
            <guid isPermaLink="false">https://medium.com/p/50e86d5ef503</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[graphql]]></category>
            <category><![CDATA[nosql]]></category>
            <category><![CDATA[dynamodb]]></category>
            <category><![CDATA[aws]]></category>
            <dc:creator><![CDATA[Maxwell Russell]]></dc:creator>
            <pubDate>Wed, 20 Jun 2018 23:03:55 GMT</pubDate>
            <atom:updated>2018-06-20T23:03:55.527Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*j0dmMfWIPoN_bUyCqv6sFA.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/photos/XfI8u5V2tWE?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Sasha Lebedeva</a> on <a href="https://unsplash.com/search/photos/building?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>I’ve really been playing around with AppSync/noSQL since discovering it. As a developer I love having control of my tools, and I have the personal goal of attempting to understand why and how things are built to be used. AppSync provides a nice simple tool to test and learn. It also provides a nice level of documented complication that allows me to think through different ways.</p><p>This desire for discovery led me through another trove of information in Amazon’s sometimes overwhelming docs. Starting with this video:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FxV-As-sYKyg%3Ffeature%3Doembed&amp;url=http%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DxV-As-sYKyg&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FxV-As-sYKyg%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/b6bfc23c6146ea7a3ca43752de23abd5/href">https://medium.com/media/b6bfc23c6146ea7a3ca43752de23abd5/href</a></iframe><p>Even without a deep practical knowledge of relational databases I found this video to be a very concise and explicative. One of the main takeaways was that I may have been thinking about things the wrong way.</p><blockquote><strong>“You should maintain as few tables as possible in a DynamoDB application. Most well designed applications require only one table.”</strong></blockquote><blockquote><strong>— </strong><a href="https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/bp-general-nosql-design.html#bp-general-nosql-design-concepts"><strong>AWS Docs</strong></a></blockquote><p>Why did this stick out so much? Well, I recently wrote an article about adding multiple items into multiple DynamoDB databases simultaneously, found <a href="https://medium.com/@MisteRussell/aws-appsync-apollo-graphql-adding-multiple-dynamodb-table-entries-simultaneously-8fc62958c676">here</a>. This was a great exploration into batch tools and cross table resolvers but I found myself asking a few different questions.</p><ol><li>If I need to search based on a value in table A, how do I return information from table B with GraphQL?</li><li>If I need to search a single query based on two fields that are shared across tables, why am I not utilizing a single table? I.e. Table A has a “title” field, and table B has a “title field.</li><li>Is there a way to create and return different aspects of a single table in the same graphQL queries?</li></ol><p>Making the decision to explore these questions has derailed my project workflow, but overall it has felt beneficial. So here is the final output from last deep dive into DynamoDB + GraphQL + data management.</p><p>I will continue to use a Recipe as my mock object.</p><h3>Data Organization</h3><p>In the multi-table model I had a table for each part of a recipe. The recipe, the elements of the recipe, and the ingredients.</p><p>In moving to a single table model my data structure has changed quite drastically. <em>Note: This is not the final data model. I will likely be making changes to the primary partition key. I’ve also avoided abbreviating for legibility.</em></p><p>I am now using a single primary partition key for all parts of a recipe, utilizing a primary sort key to differentiate between the different parts.</p><p>The Recipe has an id:</p><p><strong>87971.</strong></p><p>All high level info about the recipe is stored into a id’d type:</p><blockquote><strong>recipe87971:info1.</strong></blockquote><p>Each element is stored in an id’d type:</p><blockquote><strong>recipe87971:element1.</strong></blockquote><p>Each ingredient is store in an id’d type relative to its parent element:</p><blockquote><strong>recipe87971:element1:ingredient1.</strong></blockquote><p>All parts of a recipe can be immediately downloaded knowing only the ID of the parent recipe! This differs from doing multi-table lookups in that I am doing a single read request. As these are all key’d adjacent to each other, hypothetically this would take advantage of Amazon’s efficiency.</p><h3>Schema Definition</h3><p>The schema definition does not change too drastically between models. One minor change I have noticed is that nested items, living all on a single table now must be referenced in the parent object to be called. Thus my recipe type looks as follows:</p><pre>type Recipe {<br>  id: ID!<br>  type: ID!<br>  title: String!<br>  category: String<br>  dbtype: String<br>  status: String<br>  elements: [Element]<br>  ingredients: [Ingredient]<br>}</pre><ul><li>In my previous iteration, ingredients only lived on the Element type.</li></ul><p>A larger change in this schema definition is the return of the queries. This is where I more heavily feel the presence of GraphQL. Let’s say I’m scrolling through a list of recipe titles + brief descriptions and then find a recipe I’d like to check out. The user can click on the item, and then by using its ID we can query and compile the data in the way intended.</p><pre>type RecipeBuild {<br>  id: ID<br>  category: String<br>  elements: [Recipe]<br>  title: String<br>  type: String<br>  status: String<br>}</pre><p>Ingredients doesn’t need to be directly exposed because it can be dealt with in our resolver. This works because we aren’t returning a single item when we search by the Recipe’s ID’s. We are finding parts which we can consume as desired.</p><h3>Mapping Templates</h3><p>Now that we have the parts we just need to define how we will work with them.</p><p>Our request template stays simple, query by ID. If no adjustments were made to the response, we’d get a basic list with an array item for each item with the ID.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/403abda5a2044f258876dfdf9d38d0bd/href">https://medium.com/media/403abda5a2044f258876dfdf9d38d0bd/href</a></iframe><p>We don’t want that though. For the front-end we need to make sure data is organized to be visualized. High level info separated from nested elements. This will allow us to map over each element, as well as each ingredient contained in the elements. Ultimately something like this would be nice:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a783aced99f7835cca844e17a82c330d/href">https://medium.com/media/a783aced99f7835cca844e17a82c330d/href</a></iframe><p>The basic response for a query is a flat list, but the whole point of rolling up my sleeves and digging into the backend is so that I don’t have to do that on the front end. So after some work, and a bit of Java, I’ve ended up with this nice little data compiler.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9f59d6dcca5278a246c47ed7d4cabedc/href">https://medium.com/media/9f59d6dcca5278a246c47ed7d4cabedc/href</a></iframe><p>There are a few things going on.</p><ul><li>Each item is looked over, and depending on the its type it is thrown into an array or saved as a variable.</li><li>High level info is returned as an map attribute</li><li>Elements are given their own array to be returned as an attribute of the returned map</li><li>Ingredients are stored in their own array for later iteration</li><li>Ingredients, based on their elementId are then store in the correct element to be iterated on later. Note: you’ll notice that we aren’t directly exposing the Ingredients array in the map. That’s because it’s a map and works like JSON so we don’t have to.</li></ul><p>This response mapping template returns the following when searching for a specific ID of a Pancakes recipe:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f63d350def7fc409bec16318e39a564b/href">https://medium.com/media/f63d350def7fc409bec16318e39a564b/href</a></iframe><p>Not to shabby eh! This in addition to batch adding the db entries should keep the consume read/write capacities pretty low. I’ll won’t be able to test that until integrating this new data model into my Apollo/React client though. I’ll likely post about that next!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=50e86d5ef503" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[AWS AppSync + Apollo + GraphQL — Adding Multiple DynamoDB Table Entries Simultaneously]]></title>
            <link>https://medium.com/@MisteRussell/aws-appsync-apollo-graphql-adding-multiple-dynamodb-table-entries-simultaneously-8fc62958c676?source=rss-5ec3f8b70c39------2</link>
            <guid isPermaLink="false">https://medium.com/p/8fc62958c676</guid>
            <category><![CDATA[graphql]]></category>
            <category><![CDATA[apollo-client]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[react-apollo]]></category>
            <dc:creator><![CDATA[Maxwell Russell]]></dc:creator>
            <pubDate>Tue, 05 Jun 2018 19:36:27 GMT</pubDate>
            <atom:updated>2018-06-06T13:45:46.551Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*U3rNX59R-ryP5uSTGTrHaw.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/photos/5L7LmNvO7r4?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Aperture Vintage</a> on <a href="https://unsplash.com/search/photos/stars?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>It was a bit of a struggle trying to figure out how to use Apollo Client and AWS AppSync to add multiple table elements, across different tables. The struggle is not over yet but I intend to expose some of the process in this post.</p><ul><li>I am using AppSync with React Web, not native.</li><li>I am using Apollo Client, without the Addition of Boost.</li><li>I am not using AWS Amplify or Mobile CLI to handle authentication and backend because I started to find that it was too magical and that Cognito’s segmented logic was easier to noodle my way around.</li></ul><h3>The Data</h3><p>For my example I will be creating Recipes.</p><p>A Recipe is composed of multiple Elements.</p><p>An Element is compose of multiple Ingredients.</p><pre>{ <br>  recipeID: &quot;12345&quot;,<br>  recipeTitle: &quot;Ceasar Salad&quot;,<br>  elements: [ <br>    {<br>      id: &quot;12121&quot;,<br>      name: &quot;Dressing&quot;,<br>      recipeID: &quot;12345&quot;,<br>      ingredients: [<br>        {<br>          id: &quot;23232&quot;,<br>          name: &quot;oil&quot;,<br>          count: 0.33,<br>          measurement: &quot;cups&quot;<br>        },<br>        { <br>          id: &quot;45454&quot;,<br>          name: &quot;vinegar&quot;,<br>          count: 1, <br>          measurement: &quot;cups&quot;<br>        }<br>      ]<br>    },<br>  ] <br>}</pre><h3>Setting up your baseline GraphQL Schema in AppSync</h3><p>I am currently using AppSync with DynamoDB, a non-relational database, so have a table created for Recipes, Elements, and Ingredients. Each piece of data references the ID of the parent data, creating a trail that can be followed with the GraphQL Schema.</p><p>Schema definitions require a few different parts.</p><p>The item that you are adding.</p><pre>type Recipe { <br>  id: ID! <br>  elements: [Element]! <br>  title: String! <br>  type: String! <br>}</pre><p>The input for that item, which cannot include enums.</p><pre>input CreateRecipeInput { <br>  id: ID! <br>  title: String! <br>  type: String! <br>}</pre><p>And lastly a mutation to add the data to a table, which returns a specific type.</p><pre>type Mutation { <br>  createRecipe(input: CreateRecipeInput!): Recipe <br>}</pre><p>AppSync does a good job of creating the baseline resources needed in the Schema but certain fields will seem like they are missing to newcomers. Taking things slowly and having the <a href="https://docs.aws.amazon.com/appsync/latest/devguide/">AWS AppSync Dev Guide</a> open will help with a deep dive into how things need to work. Arrays of strings or floats can be added with ease into a single table element, but once you move to adding a new type which ultimately lives in a different table things default schema no longer work.</p><p>Testing your schema with the built in Queries options is also a great way to see how different behavior work, as well as if your resolvers are functioning correctly. Once we have confirmed that the baseline schema are creating table entries correctly (yes, the testing creates actual data!) we can add to our schema so that there is method to handle multiple items simultaneously. This is powerful to me because it leaves the enumeration out of the front-end, keeping the code cleaner.</p><p>We don’t need to recreate each piece, but we do need a new mutation because we are sending the pieces in a new configuration. For learning purposes I am going to assume that we can add multiple recipes at the same time, even though I am only sending a single recipe at a time.</p><pre>type Mutation { <br>  addRecipe( <br>    recipes: [CreateRecipeInput!],<br>    elements: [CreateElementInput!],<br>    ingredients: [CreateIngredientInput!], <br>  ) : RecipeResult <br>}</pre><p>You’ll notice that our returned item is RecipeResult. This is a new schema Type that needs to be created as well. My returns aren&#39;t working correctly at the moment though, so I&#39;m not going to dive into that yet. I will update this post when that has been handled. For now, I&#39;m verifying that things are created by checking my data sources.</p><h3>Creating Data Sources and updating IAM Roles</h3><p>The parent data source doesn’t need any additional indices for lookups, but the children do. This will allow DynamoDB to sort by the parent table item’s ID. This is an important detail primarily for queries, but if the parent item’s ID is not included in the mutation (which is a requirement so shouldn’t be an issue), then you will have broken data.</p><p>After the Data Sources are created, you can navigate to the AWS IAM Management Console to update the permissions on any of the roles that are automatically created for your tables. AppSync seems to do a pretty good job of creating the different working pieces needed to quickly(ish) bootstrap an app. We can select our parent data source RecipeTable and edit the policy so that it can handle dynamodb:BatchWriteItem for the different resources we need access to. We end up with a policy that includes the table and any sub elements for the region and account of our app.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/53d798361f60c827d2666aed05ec5d42/href">https://medium.com/media/53d798361f60c827d2666aed05ec5d42/href</a></iframe><h3>Creating the Resolver to Enumerate</h3><p>Without leaving AppSync we can now create the resolver for our new mutation. Why can’t we use one of the automatically generated resolvers? They don’t handle Batch Writes to our DynamoDB table. When adding a new custom mutation AppSync automatically creates an empty slot for a Resolver. This allows you to define custom logic for resolvers across the board. With these we are able to restrict view access, add additional information to data server-side, and a slew of other functionality can be added. I find this a a powerful tool for cleaning up some front-end responsibilities.</p><p>For our addRecipe mutation, we create a new Resolver for the RecipeTable that is also being used when creating a standard Recipe table entry. For my Primary Index I used the id field on the Recipe. I don&#39;t care about sorting these on the backend because I have not made decisions yet about how I want to present these to users.</p><h4>Request Mapping Template</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0a70d01ef92647f6e2650ad11f53d347/href">https://medium.com/media/0a70d01ef92647f6e2650ad11f53d347/href</a></iframe><p>The request mapping template looks over each of the different types I pass in with GraphQL, creating an empty array so that it can enumerate over the request and then fill an array is each of the items. For the Recipe I am also adding an author field which is the Cognito username of the user who created the item. This gets passed through automatically as my API is using Amazon Cognito User Pools to authenticate GraphQL calls (I&#39;ll go over this in another post).</p><p>Each item in the array is automatically mapped with the built in DynamoDB utilizes on AWS. Que magic! J’adore.</p><p>The last, very important detail of the Request Mapping Template that needs to be handled is setting the operation to BatchPutItem. This is how the resolver knows it is going to need to handle multiple pieces of data for one, or more tables.</p><h4>Response Mapping Template</h4><p>There are Response mapping templates for Batch Operations that can be used. These do not return correctly for me currently. I will update this part of the post when I discover why.</p><h3>Creating the React Component</h3><p>I’m not going to do a complete walkthrough of creating the component, because this is post is about sending multiple items. For a full walkthrough this post by Nader Dabit was quite helpful, <a href="https://tylermcginnis.com/building-serverless-react-graphql-apps-with-aws-appsync/">Building Serverless React GraphQL Applications with AWS AppSync</a>.</p><p>First a .js file needs to created to save the GraphQL. If you were succesful at saving in the AppSync tools then you have the basic idea. Things look a bit differnt in production though:</p><pre>import gql from &#39;graphql-tag&#39;;</pre><pre>export default gql`<br> mutation addRecipe( <br>  $recipes: [CreateRecipeInput!]<br>  $elements: [CreateElementInput!]<br>  $ingredients: [CreateIngredientInput!] <br> ){ <br>  addRecipe( <br>    recipes: $recipes<br>    elements: $elements<br>    ingredients: $ingredients <br>  ){<br>   recipes { id }<br>   elements { id }<br>   ingredients { id } <br>  } <br>} <br>`</pre><p>The main different is that there are variables defined $recipes that store the information and then get sent to the AppSync mutation. These prep the data to be sent along. From this mutation we can make the general assumption that we are going to need 3 arrays. One for each table we need to send data to.</p><p>Now, this is where I hit a pretty large roadblock. I knew that I needed to structure my data from the AddRecipe component such that I was sending an array of objects. Each object being either a Recipe, Element, or Ingredient. Apollo&#39;s docs for the Mutation component didn&#39;t go into depth about how to send this type of data along. Eventually I was able to use mutate variables, which seemed to contain the data correctly. You&#39;ll notice that I am using compose with only a single graphql function, that&#39;s for thinking ahead in case functionality needs added to the component.</p><pre>export default compose( <br>  graphql(AddRecipeGQL,{<br>   props: props =&gt; ({ <br>    addRecipe: (recipeData) =&gt; props.mutate({<br>    variables: { <br>      recipes: recipeData.recipes,<br>      elements: recipeData.elements,<br>      ingredients: recipeData.ingredients,<br>    }, <br>    optimisticResponse: {<br>      __typename: &#39;Mutation&#39;,<br>      addRecipe: {<br>        ...recipeData, <br>        __typename: &#39;Recipe&#39;<br>      } <br>    } <br>   }) <br>  }) <br>}), <br>)(AddRecipe);</pre><p>The graphQL-tag .js file is imported as AddRecipeGQL and passed to a graphQL function. This keeps thinks a little cleaner than if the GraphQL mutation was embed directly into the Apollo function. Into my props mutation I pass a variable recipeData which is an object of arrays for each set of data that I&#39;m trying to create.</p><p>In my variables parameter I then define the variables that need passed into the GraphQL mutation mentioned above. This is how Apollo knows which data is related to the variable passed through the props mutation. Passing in the variable without theses throws errors and data is not updated.</p><p>The optimisticResponse is used to immediately update local data, for UI purposes, while a response is pending from the server. It is passed all recipeData with a single __typename for the recipe.</p><ul><li>Unforunately Apollo is throwing me errors requesting some additional __typename for the smaller pieces of data, but until I can dig into if these are needed both server-side and on the front-end I will not add them.</li></ul><h3>Why AppSync?</h3><p>I like this setup because it is fast and offers a lot of out-of-the-box functionality for offline storage. Setting up my own backend for data, with control of what is returned and how takes a lot of extra logic off the front-end. It moves the front-end closer to input/display-only rather than something that needs to worry about stamping data, over-complicated endpoint calls, or managing API calls to update data. Now that I have the basics down it is a comparatively quick thing to bootstrap to get things up and running. The options to reach out to Lambda functions also interests me as a future integration.</p><p><em>Originally published at </em><a href="https://gist.github.com/misterussell/983eb05bd96c5872c7a2d4fde26da60f"><em>gist.github.com</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8fc62958c676" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Conway’s Game of Life in JavaScript — Part VIII — Array Manipulation]]></title>
            <link>https://medium.com/@MisteRussell/conways-game-of-life-in-javascript-part-viii-array-manipulation-9e0b7d3f7158?source=rss-5ec3f8b70c39------2</link>
            <guid isPermaLink="false">https://medium.com/p/9e0b7d3f7158</guid>
            <category><![CDATA[array-methods]]></category>
            <category><![CDATA[reactjs]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Maxwell Russell]]></dc:creator>
            <pubDate>Tue, 08 May 2018 22:25:40 GMT</pubDate>
            <atom:updated>2018-05-08T22:25:40.681Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fKd1OIfgYxAFpFKqCRjfYA.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/photos/zc4zlco207A?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Aleksander Naug</a> on <a href="https://unsplash.com/search/photos/spraypaint?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p><strong>Quick update: </strong>Still trucking along with this project! I’ve hit a major roadblock with re-renders. Things start to lag once I hit around 150 components with 0.33–0.75 of the components updating every 500ms; I understand fully that React isn’t a tool that was intended to be used for game production. That being said, I’m still investigating with React because there are a few other features I want to explore that I think will be valuable to my toolbelt regardless of the final outcome of the game.</p><p>I’ve also began exploring d3 as an alternate solution to drawing my grid. This has some of it’s own hurdles to tackle, which I’ve got on my backburner.</p><p>Now onto today’s topic:</p><h3>Array Manipulation!</h3><p>The goal is to turn this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3D8-gFPrEaxjilO6V4sT3g.png" /></figure><p>Into:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/509/1*BkW-HVQT7OoF7nANqVQeUQ.png" /></figure><p>This is a spaceship. A known configuration of Conway’s game of life that always acts the same. I’ve known that eventually I would like to let user’s select one of these, without having to manually count each cell, miss a few and screw up the gameplay. So, using the <a href="http://conwaylife.com/ref/lexicon/lex.htm">Life Lexicon</a> I was able to scrape some basic configurations convert them to binary arrays for use in my app.</p><p>There are three things needed to be able to successfully convert one of these configurations into my setup.</p><ol><li>The data that represents which cells of the configuration are alive/dead</li><li>The number of indices that make up a single row of the configuration. You’ll note from the raw array up top that there is no delimiter to follow. I’m grabbing these when I scrape them from the Lexicon.</li><li>The size of the gameboard that the user is currently looking at.</li></ol><p>I’m only presenting configurations to the user that fit into their current gameboard. This eliminates having to manage them trying to play something that is larger than what is available. So, knowing this, I know that as long as the length of row for each configuration is less than the length of a row of the gameboard we are in business.</p><p>I’ve found that the best way to manipulate an array that needs to visually represent a square or rectangle is to convert it to an array of arrays.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6DT-QDqLPf7BcrMhMnCL2A.png" /></figure><p>With that you then need to decide where in the gameboard these cells need to be located. I’ve chosen with the middle, or for arrays that aren’t comprised of odd rows, slightly to the right/below of the middle. Once you know generally where things need to sit you can began creating the new arrays (never mutating!). I’m storing the top/bottom and left/right padding as array pairs, i.e. [0, 1] where there needs to be an extra cell added to the right of the array but nothing on the left.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-AZV7HKUBQ2cYS6VfI7GDg.png" /></figure><p>The findPadding() function is separated out as standalone logic as it can technically used for both scenarios, where the original stacked array needs to be stretched wider, or taller.</p><p>That brings us to the problem of figuring out how tall an array is. I’ve chosen to handle this similarly to how I’m finding the row padding. I use the total length of the array and the length of the rows of the configuration to gather this. I could also use the length of the array of arrays, but this seems incongruent.</p><p>So, this B29 with a row length of 17 looks like this before it is to be fit onto our square grid:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lsj-HT1uWmfgAWTRy52Y2w.png" /></figure><p>Let’s say the user is currently staring at a 21 x 21 grid. We can expect some additions that need to be made.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*msJKbySxaIt0TpanDwz7cw.png" /></figure><p>Padding the rows isn’t too difficult with the help of the spread operator:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9VUFpGOaNfqFGWHue-e4AQ.png" /></figure><p>Padding the top/bottom took a bit more noodling. It requires that we know the length of a whole row on top of knowing how many rows need to be padded on the top and bottom. So I end up with a function redraw() that finds how much our columns need to be padded on the top and bottom, pad my rows, taking a quick peek at how long a row is, and then create my padding for the top and bottom.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lqYLgj6Sf2eJ9ZXiWMwI0A.png" /></figure><p>The trickiest bit here isn’t reducing the array’s to a flattened array. It was actually trying out how to create multiple arrays of zero, [0, 0, 0, 0], with nothing more than an integer.</p><p>First we create an array of empty arrays, so that there are the number we will end up needing to fill.</p><pre>Array(4).fill([]);<br>// returns<br>[[], [], [], []]</pre><p>We can then map over these and replace the empty array with a filled array.</p><pre>Array(4).fill([]).map(() =&gt; Array(2).fill(0)); <br>// returns <br>[[0,0], [0, 0], [0,0],[0,0]]</pre><p>And — since we are returning only copies at each instance our original array never gets messed with!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9e0b7d3f7158" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Conway’s Game of Life in JavaScript — Part VII — Stateless Components]]></title>
            <link>https://medium.com/@MisteRussell/conways-game-of-life-in-javascript-part-vii-stateless-components-cd3a0451e28e?source=rss-5ec3f8b70c39------2</link>
            <guid isPermaLink="false">https://medium.com/p/cd3a0451e28e</guid>
            <category><![CDATA[react]]></category>
            <category><![CDATA[mobx]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[pure-function]]></category>
            <dc:creator><![CDATA[Maxwell Russell]]></dc:creator>
            <pubDate>Wed, 18 Apr 2018 22:38:43 GMT</pubDate>
            <atom:updated>2018-04-18T22:38:43.154Z</atom:updated>
            <content:encoded><![CDATA[<p>Woah Nellie! That was a jump.</p><p>In this weeks exploration of JavaScript through Conway’s Game of Life I’ve moved away from using create-react-app in favor of a less bottlenecked bootstrap <a href="https://www.npmjs.com/package/simple-react-app">simple-react-app</a> from <a href="https://medium.com/u/a197f91c90b6">Francesco Agnoletto</a>.</p><p>Why switch now, after I did all that work? Because I wanted to check out <a href="https://mobx.js.org/">MobX</a> and I couldn’t get decorators to work in create-react-app without ejecting. There are a few other reasons I decided to move away from create-react-app as well, but they aren’t relevant to this project. Here’s a nice breezy field to represent not having to worry about state in components and how I felt when I got @ decorators to work:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KaWHiDLdKvUUqshN41f5qQ.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/photos/hZX_efxYt_M?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">John Such</a> on <a href="https://unsplash.com/search/photos/fields?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><h3>Major Change — Stateless Components</h3><p>I’m always reading that it is better to have stateless components when you can. Considering that this project isn’t making async requests to external API’s I figured it would be a good place to get some practice creating components without state. Overall — there isn’t a lot going on in the app and only one component had state. There are some buttons and a grid of divs. Well, actually, there is a lot going on to get just those things; credit is due! I’ve been reworking this over and over. It took me about 2 days to get everything stateless and moved into MobX stores. And BOY do I like it.</p><h3>Benefits?</h3><p>Overall I like how much cleaner the main game component has become. I was able to minimize it down to the grid, buttons (with relevant click handlers), and a containing div. No additional component functions for changing the shape of data, or updating it. That is all handled in the stores.</p><p>The gameboard component really only needs to know one thing to correctly render itself. An array of 0&#39;s and 1&#39;s. The number of columns and rows, and the size of the cells can be derived from that. Changing the number of indices in the stored array and voila, updates to the dom.</p><p>The interactions with the different pieces of the component only need to know whether or not the game is already running. If it’s running you shouldn’t be able to click anything except to stop the game.</p><p>I suppose it is debatable whether or not my interval should live on the component, but as long as the interval is cleared at the store level if the observable is no longer observed, that should take care of things?</p><p>I have separated the Game of Life into three stores:</p><ol><li>The Grid UI — This calculates the dynamic sizing of the grid component.</li><li>The Gameboard State/Logic — This calculates how many cells should be present, what their values should be, and what may change about their values.</li><li>The Gameplay State — This tracks whether things are moving along, or stopped.</li></ol><p>I’m not integrating the Grid UI into the Gameboard Store, but it does rely on knowing how many cells are currently available to generate it’s specs. As it is purely a visual structure, I fell this is appropriate.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*X1j9V44iE4XQXxFs5gK7dA.png" /></figure><p>The Gameplay logic also reaches out to the Gameboard Store, as it needs to set an interval to keep the game running while cells are alive, forcing the visual to re-render. I’m able to reach between stores because each store is bound to the rootStore, parent store.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tBoqe0WfRYc_N4rwvV6A1Q.png" /></figure><p>The Gameboard then controls itself with just a few key pieces of information. I define the minimum number of rows/cols that the grid can have, the number of rows/cols that the user may have added and a hashMap that is used to generate the subsequent cell’s values.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*thgAs-RYR2CR083JyM4b4Q.png" /></figure><p>Note: I am treating my stores as collections and models to try to keep some form of integrity into the way I organize my files/data, but I think I need to investigate best practices a little more for this.</p><h3>Reworking other components</h3><p>Most of my other components haven’t really changed much. At least I seem to have been on the right track. Here’s a comparison of the Grid Component before and after. Overall there’s some syntactical differences, but mostly stays the same :</p><p>Before:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LY7SjOQ0W69fAMwpc1DdJQ.png" /></figure><p>After:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QuaOp6Ly56G4WerPXygLhg.png" /></figure><h3>Flaws?</h3><p>There are flaws in everything. We are developers. Flaws are our bread and butter?</p><p>After refactoring this into a mixture of pure function components and bare-bone class extensions the heavy lifting immediately feels less functional to me. I was using classes (factories really) to handle data manipulation in the earlier version of this, but I was freezing things my factories produced. This made things immutable. I liked that. I need to continue to refactor the newer class stores to get them back to how I had it before.</p><h3>Linting Rules</h3><p>This didn’t end up just being a copy and paste voila! The linting rules from AirBnB’s style guides had me rewriting a lot of code. I used their style-guides prior to adding the rules to my linter but this really put the foot down on keeping things consistent</p><ul><li>It put my over-use of nested ternaries in check: I have spent a lot of time thinking through semantic ways to name nested ternaries, so I don’t love this rule but will stick with it for now.</li><li>Drastic overhaul of arrow functions: I didn’t realize how inconsistent I was with {}’s.</li></ul><h3>What’s next?</h3><p>I do not like the way that I have to pass props into my link. I need to spend some time reading up on the Context API to get past this.</p><p>Check out where I started on this project to see how much it has changed! <a href="https://medium.com/@MisteRussell/optimizing-conways-game-of-life-in-javascript-part-i-a237039e3d26">Part I.</a></p><p><em>Originally published at </em><a href="https://gist.github.com/misterussell/b780b4292267bac1e7d0d2b8587a6837"><em>gist.github.com</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cd3a0451e28e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Optimizing Conway’s Game of Life in JavaScript — Part VI]]></title>
            <link>https://medium.com/@MisteRussell/optimizing-conways-game-of-life-in-javascript-part-vi-5e4f1438960a?source=rss-5ec3f8b70c39------2</link>
            <guid isPermaLink="false">https://medium.com/p/5e4f1438960a</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[array-methods]]></category>
            <dc:creator><![CDATA[Maxwell Russell]]></dc:creator>
            <pubDate>Fri, 13 Apr 2018 22:38:44 GMT</pubDate>
            <atom:updated>2018-04-13T22:38:44.420Z</atom:updated>
            <content:encoded><![CDATA[<p>Array manipulation, and tigers, and bears oh my!</p><h3>The Issue</h3><p>One aspect of my game grid that I did not like was that if a user selected some cells and then changed the size of the grid the cells jumped all around the board. I understood when creating the rendering logic that this would happen but I choose to leave it in the icebox until things were mostly working.</p><p>Let’s say the user selected this nice little T:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/510/1*GAdEz7ioSWMutn14LloZcA.png" /></figure><p>If they grew the size of the grid once the nice little T becomes this mess:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/505/1*vRb1hyNUmsl8MrAj8nBhYQ.png" /></figure><p>Or, if someone selected this little cross with a square from a larger grid:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/507/1*7JL5ap2yqJI_DAz9CIpVZg.png" /></figure><p>And chose to reduce the size of the grid quite drastically they end up things not only being chopped up but also rearranged:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/508/1*2KAMYF9Prm7V0A5ggGrE2w.png" /></figure><p>Now that doesn’t look very nice does it?</p><h3>Fix 1 — Growing the Grid</h3><p>Fixing this was relatively easy because I already had a function that turned the flat grid of cells:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dWXqA9xf2bx7OG7fPOVEew.png" /></figure><p>Into a stacked array:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bsejmxapKR8f55fyl5MBJw.png" /></figure><p>At first, I had only been thinking in terms of updating the flat array, pinpointing how many indices would get inserted before the first cell, and then between the 6th and 7th etc… I quickly realized that if I just turned them into separate chunks I could probably just concat each changed array together faster.</p><p>My growCellArray(array, alpha) takes two arguments. The original flat array and the alpha of how many cells need added to the total width/height of the array. I start with a 5x5 array, and pass in an alpha of 2, generating a 7x7 array.</p><p>I know that we will need to stack an array of dead cells at the top and bottom so first create that.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lVaRgR3b4-kZ_6VCMRnmMw.png" /></figure><ul><li>I use the Array.from() method pretty frequently through out the project so stuck with that.</li><li>We can get the dimensions of the grid by getting the square root of the flattened array’s length, which I can then add my alpha to get the length of a new row.</li></ul><p>Next we need to handle updating the arrays that already existed, that may or may not have active cells that the user has selected. All that changes within these rows is the front and end of the arrays. There will always be an additional number of alpha/2 cells tacked on to each side.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ilhVY6TOYYbF5N3hDbJY8w.png" /></figure><p>Thus I convert the flat array into its subarrays and then pad each side with the new cells. The spread operator makes this a breeze.</p><p>Returning was a bit more complicated because I can just spread these together because my updatedRows section is a single array of other arrays. So, I need to concat them together.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ekxDSku8nfmtZcqvJvUBrw.png" /></figure><p>So now, this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/510/1*GAdEz7ioSWMutn14LloZcA.png" /></figure><p>Becomes a smaller T, maintaining its neighbors and relative position:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/509/1*6y9yw1E_xr0FHGQ3HWwVlA.png" /></figure><h3>Fix 2 — Shrinking the Grid</h3><p>Shrinking works different because pieces of the array are being destroyed at each turn. The same arguments are needed though. The array of the current state and the alpha representing what we will be chopping off.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fTmJ7OFlyisPb1bi15qh5Q.png" /></figure><ol><li>I first break the everything down to their subarrays.</li><li>I then return an array with the first and last sections removed, for each subarray.</li><li>I then filter on all of the subarrays and get rid of the first and last.</li><li>Then I put all of the arrays back together to get the flattened array that my rendering uses.</li></ol><h3>Side Note</h3><p>I’m chaining a few different methods together here and using a ternary as well, but I strive to keep these sorts of things readable. Proper spacing and naming is crucial for being able to understand things later. I’ll sometimes be reading through stack overflow and see posts that boast the few characters used to create something. How the hell is that helpful? I suppose the example above could be complicated if one weren’t familiar with the different array methods, so commenting could be useful in that case. Avoiding the semantic concerns of aptly naming each step of editing saves some confusion, should I picked ridiculous variable names. I like a nice blend of properly named variables to store things and chained together methods in more complicated scenarios.</p><p>Here’s the product of our finalized shrink function. Our T and Square change from:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/507/1*7JL5ap2yqJI_DAz9CIpVZg.png" /></figure><p>To a bigger relatively positioned:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/509/1*CusZ1IsNKRJqwJk9z8eaVQ.png" /></figure><p>In the current iteration, if cells move off the gameboard they are deleted permanently. I may decide to persist these deleted cells until the Start button is clicked but I’ll leave that in my icebox for now.</p><p>More to come!</p><p><em>Originally published at </em><a href="https://gist.github.com/misterussell/20f3b766517a5d4b1d001508932c5431"><em>gist.github.com</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5e4f1438960a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Optimizing Conway’s Game of Life in JavaScript — Part V]]></title>
            <link>https://medium.com/@MisteRussell/optimizing-conways-game-of-life-in-javascript-part-v-1fe4845dbdef?source=rss-5ec3f8b70c39------2</link>
            <guid isPermaLink="false">https://medium.com/p/1fe4845dbdef</guid>
            <category><![CDATA[reactjs]]></category>
            <category><![CDATA[css-grid]]></category>
            <category><![CDATA[code]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Maxwell Russell]]></dc:creator>
            <pubDate>Wed, 11 Apr 2018 20:16:54 GMT</pubDate>
            <atom:updated>2018-04-13T17:06:40.709Z</atom:updated>
            <content:encoded><![CDATA[<p>In this post I’ll be discussing a distinct feature of the app rather than decision making as a whole.</p><p>The goal: to recreate the game board with a static visual representation of the cells and the sum of their lives or deaths.</p><ul><li>A cell with the greatest value will be a specific colour.</li><li>Cells will lighten in colour as the values are smaller.</li><li>A cell that was alive 0 times will be white.</li><li>A cell’s shade will be dynamically generated rather than utilizing an array of precomputed colour values.</li></ul><h3>Initial Decisions</h3><p>I am creating a new Grid Component, rather than recycling the component used in the live game. I’m choosing this path rather than refactoring the live grid because the use-cases are quite different. There are no onClick functions on the new grid, array computations and rendering take different values, and the new grid is computing different state based on what was passed in from the parent Stats page not the active game logic.</p><p>Edit: I realized I had already built a flexible grid component so I don’t need to actually recreate visual grid. I’m just passing it the original game grid settings and then adding stat related functions on the new component.</p><p>The data to populate the grid comes through props as a flattened array with cumulative integers that represent that stat I am trying to illustrate.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jYzwXbnEJuYij1Jxvs88LA.png" /></figure><p>Here’s the initial rendering:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/252/1*2H5-PIxMRLkjLQFKEkHYOA.png" /></figure><p>Based off this array I am choosing to send the value of each index, an alive or dead flag, and some sort of &quot; shade indicator&quot; to the child cell component.</p><ul><li>The value is mostly for dev purposes and can potentially be used in a toolTip.</li><li>The alive/dead flag is going to be used for colour selection.</li><li>The shade indicator is something that needs to be dynamically generated by the parent Grid, as the cells don’t have any reference to each other.</li></ul><p>Note: I’m inline styling these components due to their dynamic generation. If I can gleam the logic to translate it into CSS I will move the styling off the components. I’m not in love with the idea of mixed styling, but I think styling these smaller components/parts inline doesn’t overcomplicate the components. I may choose to keep CSS files for these built and commented out for transparency.</p><h3>The Logic</h3><p>Rather than integrate a complicated colour manipulation library I’m using <a href="https://stackoverflow.com/questions/5560248/programmatically-lighten-or-darken-a-hex-color-or-rgb-and-blend-colors">this nice little vanilla converter</a>. It takes a float from -1 to 1 and a hexadecimal colour value as it’s parameters and returns a hex colour value such that -1 is the darkest version of that colour and 1 is white.</p><p>I have no negative values to worry about so only need to throw in 0–1 values; 0 being the highest value cell and 1 being a cell with no value. Here’s how I’m creating a reference object to get the shades of the different cells:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XEEQB598gd5xcpTkQJy4qg.png" /></figure><p>This is new syntax so I’m going to break it down.</p><ol><li>Define an empty array.</li><li>Send the sorted flat array into a new <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set">Set</a> to get all of the unique values. I sort from largest to smallest as the largest value needs a shade of Zero; the index of the sorted value represents this.</li><li>For each of those values define a key:value pair in a referenceable object.</li><li>Rather than try to mathematically compute the decimal values for each of these whole numbers I’m using javascript’s flexible nature to build a string which I then coerce into a number. Hoorah. I would handle this differently if these weren’t whole numbers.</li><li>This object is then set to state to be used when the component mounts.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iuaiopoS1LLDJZmgkuKd7Q.png" /></figure><h3>The Initial Product</h3><p>These steps give us a baseline component that shades each cell depending on its total value. I’ll continue integrating functionality onto these once I hit my MVP.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/272/1*_0MoCxJoWM-x8Ns1QvuDdw.png" /></figure><p>There are I will need to handle here:</p><ul><li>These variance in the different colours needs to be bumped up so that is more noticeable between similarly valued cells.</li><li>I’m only accounting for two flags, which isn’t very flexible.</li></ul><p>Catch up on the rest of the series! Read from the start <a href="https://medium.com/@MisteRussell/optimizing-conways-game-of-life-in-javascript-part-i-a237039e3d26">here</a>.</p><p><em>Originally published at </em><a href="https://gist.github.com/misterussell/a64be6a91d34fcf3de8f467f74b1cb1f"><em>gist.github.com</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1fe4845dbdef" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Roadblock, re-routing. React Router v4]]></title>
            <link>https://medium.com/@MisteRussell/roadblock-re-routing-react-router-v4-26ea01bc707?source=rss-5ec3f8b70c39------2</link>
            <guid isPermaLink="false">https://medium.com/p/26ea01bc707</guid>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Maxwell Russell]]></dc:creator>
            <pubDate>Tue, 10 Apr 2018 01:17:42 GMT</pubDate>
            <atom:updated>2018-04-10T01:17:42.967Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Gi6hbyvbpMkiXyK_NLGsoQ.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/photos/7S2PJ5KjoL8?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Lena Köhler</a> on <a href="https://unsplash.com/search/photos/traffic?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>This is a shallow dive into a recent roadblock I encountered with react-router v4. Routing with the previous build was handled with pushing to history in props. v4 seems less direct and the new behavior seems to keep logic segmented rather than throwing 100 routes together in the index router, which I like. In this recap I will be referencing my optimization of <a href="https://medium.com/@MisteRussell/optimizing-conways-game-of-life-in-javascript-part-i-a237039e3d26">Conway’s Game of Life</a>. The challenge: to properly render a child route such that:</p><p>/stats/gameOfLife renders on navigation to that URL and all other components are unmounted.</p><p>Typically in prior releases I would have handled this in my routes module:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3Yk6avF0MySaaIKhV805hg.png" /></figure><p>In v4 this moves out of the routes module and actual into the parent component. I.E. if we want to render a child of stats, we must let stats handle that rendering. Here’s how I have my initial stat component rendering:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wNFQyHlubG7VaA15Z1y2EQ.png" /></figure><p>I like this pattern. It does make more sense from a structural standpoint. Your parent must always render first to get access to the subroute. This let’s the parent handle swapping around the different subroutes.</p><p>Another issue I initially ran into was how to handle routing. I’m used to using &lt;Link /&gt; for my initial navigation paired with pushing to history for continued navigation. Moving away from pushing to history and wrapping my navigation in another link took me some time to get to. I kept trying to reach out beyond the component to make changes.</p><p>So, using a button to navigate to a new URL now looks like:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/806/1*sz_CX-HqOcCc61oHcj6Azw.png" /></figure><p>I find this a little more declarative. Maybe that isn’t the right word. Now I can handle passing in the computed props from one component to another without having to send them to state. This may change, but initially seems like a streamlined way of passing info around while programmatically navigating.</p><p>Sidenote: If you want subroute navigation to work correctly, make sure you are using the subroute URL you made and not just making a new one up in the other component, because nothing new will render. Because the route does not exist.</p><p><em>Originally published at </em><a href="https://gist.github.com/misterussell/3c42dd812e2358cf6843a5d4b934f660"><em>gist.github.com</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=26ea01bc707" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Problem of the Day: Adjacent Equals]]></title>
            <link>https://medium.com/@MisteRussell/problem-of-the-day-adjacent-equals-71731fedf3f2?source=rss-5ec3f8b70c39------2</link>
            <guid isPermaLink="false">https://medium.com/p/71731fedf3f2</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[coding]]></category>
            <dc:creator><![CDATA[Maxwell Russell]]></dc:creator>
            <pubDate>Tue, 27 Mar 2018 18:55:34 GMT</pubDate>
            <atom:updated>2018-03-27T18:55:34.405Z</atom:updated>
            <content:encoded><![CDATA[<p>Issue: Count adjacent equal values in an array, so that the number of values in distinct groups can be used at a later time. Example:</p><pre>[0, 0, 0, 1, 1, 1, 1, 0, 1, 1, 0]; </pre><pre>// should return </pre><pre>[3, 1, 1];</pre><p>This array has 3 groups of 0’s. A group of three and 2 groups of one. The goal was to return an array of these values as such: [3, 1, 1]. I can then compute averages, etc…for these groups.</p><p>I struggled with this for a few hours before using a brutish method which iterates over just the array.</p><pre>function getGroups(arr) { };</pre><p>Originally I tried to handle this with a loop that computed the sums during iteration and then spat these into their own arrays. This kept failing because the sums were 1 short, or returning NaN. I settled on chopping these up into sub-arrays to make things more manageable.</p><p>I define my storage for the subArrays, as well as something to track what array within my storage I will need to put my values to sum:</p><pre>let zeroStorage = [];<br>let zeroCount = 0;</pre><p>The intention behind having a count, is so that I can keep track of the current index within the storage and only put digits into that index should they meet my requirements. If it doesn’t exist, I create a new array for that new instance of my integer. I’m using the spread syntax to keep away from mutating the original array.</p><pre>for (var i = 0; i &lt; arr.length; i++) {<br> if (arr[i] === 0) {<br>   zeroStorage[zeroCount] === undefined <br>     ? zeroStorage[zeroCount] = [1] <br>     : zeroStorage[zeroCount] = [...zeroStorage[zeroCount], 1];<br> } else zeroCount += 1; <br>};</pre><p>Because I am adding one to the zeroStorage array every time an index does not equal zero empty array slots are created. I am eliminating these with a filter, rather than trying to bend the logic to stop creating them as it was a simpler solution. I then map/reduce the leftover arrays to get just the totals for each subarray.</p><pre>zeroStorage.filter(n =&gt; true) <br>           .map(subArr =&gt; { <br>             return subArray.reduce((a, b) =&gt; a + b); <br>           });</pre><p>Et voila, our shiny array for of [3, 1, 1].</p><p>This may not be the most sophisticated code as it relies on repeat iteration, but hey I’ll take it! I am implementing this to filter on arrays of 0’s and 1’s so am not explaining how to elaborate to loop over other values.</p><p>Thanks for reading! Find the full code <a href="https://gist.github.com/misterussell/63db165b9caf0b8b14483789a5bcf0d3">here</a>.</p><p><em>Originally published at </em><a href="https://gist.github.com/misterussell/88574082c9c1df26bdfde8654689ffd4"><em>gist.github.com</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=71731fedf3f2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Optimizing Conway’s Game of Life in JavaScript — Part IV]]></title>
            <link>https://medium.com/@MisteRussell/optimizing-conways-game-of-life-in-javascript-part-iv-d354abd4e2fc?source=rss-5ec3f8b70c39------2</link>
            <guid isPermaLink="false">https://medium.com/p/d354abd4e2fc</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[code]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Maxwell Russell]]></dc:creator>
            <pubDate>Tue, 27 Mar 2018 14:16:03 GMT</pubDate>
            <atom:updated>2018-03-27T14:20:36.193Z</atom:updated>
            <content:encoded><![CDATA[<p>Content with my initial product, albeit a few bugs, I’m switching gears away from the UI/UX to work on one of the initial features that I wanted to integrate into this project. DASHBOARDS. Well, the logic behind them at least. Have to start somewhere!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*x3s-gHII_wdglfzpMD6tgA.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/photos/4eTnTQle0Ks?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Alvaro Reyes</a> on <a href="https://unsplash.com/search/photos/puzzle?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><h3>Somewhat unimportant information that I’m choosing to write it down.</h3><p>I do a lot of my initial building at work, outside of my actual dev environment. This is both a challenge and an interesting way of doing things. One of the main reasons for this is because I work on a Mac at home and a PC at work and prioritize writing code, rather than researching how to replicate my dev environment on another OS. Priorities change, but until this one does, I will continue to work this way.</p><ol><li>I work with attention towards programming <em>functionally</em>. By not having access/deciding not to replicate the exact state of my app outside of the project I have to be very mindful of what I do have access to. I’m not grabbing random parts of state, or relying too much on the functions on the view to do my calculations.</li><li>I effortfully <em>refactor</em>. My initial test cases don’t necessarily follow the way I have data organized in my app state. I allow myself time to make judgements on what I am integrating. This happens on two levels. One level is addressing whether or not the data has a use. Frivolous data only complicates state. The second level is whether or not the structure of the data I am integrating is organized in an efficient way. Am I doing too much iteration, is there a way to access nested data more cleanly? Am I keeping functions simple and relying on as few possible variables as possible (or a single object).</li><li>I do not get distracted by <em>non-priority</em> functionality. Bugs don’t exist when they aren’t in the code! If I’m working on a specific block of functionality in my non-dev environment I don’t have the option of toying around with Modal display delays, or fiddling with my Bootstrap component styling. I can get right to the root of what I’m trying to tackle.</li><li>I loose out on <em>early stage unit tests</em> for the new functions. I’m testing at the console level frequently when getting into the initial code. This creates more work, but I do get more familiar with the structure of the data when I bring it in. Thus writing test cases becomes faster when integrating.</li><li>The sleeper <em>awakens</em>. Uncluttered code leaves a lot to be imagined! I keep it simple and I’m not trapped by my previous unnecessary complications. Sometimes this even means I end up fixing those. I am a giant Dune nerd.</li></ol><h3>Choosing What to Track</h3><p>As the game is rather quick-moving and doesn’t leave a lot of opportunity for creative user actions I’m focusing on data. Data about the cells and the game board as a whole, not user-centric data. What cells people pick to start the game with does not interest me, yet. A few examples of what I am tracking:</p><ul><li>Which cell/s had the longest periods of uninterrupted life</li><li>Which cell/s regenerated the most?</li><li>Did a single cell regenerating cause a noticeable effect on subsequent generations?</li><li>Were some areas of the game board noticeably more active than others?</li></ul><h3>Initial Setup for Tracking</h3><p>For my pre-integration data I am utilizing an array of objects to represent the different generations over time. My app only tracks one object replacing the object with the next iteration of the object. The intention behind this is to curb the amount of data I’m storing should the game last for a few hundred iterations.</p><p>I am tracking with two objects.</p><ol><li>An object to track the singular cell’s activity.</li></ol><pre>let cellTracking = {}</pre><ol><li>An object to track the group of cells as a whole. This is currently comprised of only 2 arrays.</li></ol><pre>let lifeBoardTracking = { <br>  generationLifeSums: [],<br>  generationDeathSums: [] <br>};</pre><p>The data is generated with a single forEach loop over the object arrays. I predict that I will move away from this during integration as the data will be tracked by state so updates will be made step by step, not recursively. I’m not going to discuss this iteration as it is a standard process. See link for full code at bottom of the article if you need an example of how I’ve done this.</p><p>The bulk of my code is handled in this loop. I’m using destructing to define variables that I return to the main cellTracking object. In this way I take what already existed and return a copy with all previous data intact.</p><pre>return cellTracking[key] = { <br>  cellHistory,<br>  cellStateSum,<br>  count, <br>  averageLife: cellStateSum/count, <br>  sustainedPeriods,<br>  births,<br>  deaths<br>};</pre><p>An example of one of our hashed cells with their cell specific information below. This gives me enough information to start plotting data onto charts. Now just to decide if these should end up on an hide-able modal, or keep things more accessible and have the dashboard persist until another game is started.</p><pre>92917664: { <br>  averageLife = 0.466666666666667,<br>  births: 3, <br>  cellHistory: [1, 0, 0, 0, 1, 1, 1, 0, 1, 1, 0, 0, 1, 0, 0],  <br>  cellStateSum: 7,<br>  count: 15,<br>  deaths: 4,<br>  sustainedPeriods: { <br>    death: [3, 1, 2, 2],<br>    life: [1, 3, 2, 1] <br>  } <br>};</pre><p>This is just the start of the data. I also intend to use tracking to target looped patterns or patterns that become stale and unchanged. I predict that I will persist these sorts of patterns so that they can looked up later, adding a more historical synopsis of app use that goes beyond the immediate play/stat format I’m starting with.</p><p>See the full code <a href="https://gist.github.com/misterussell/ab8aba1580f4bf86ddeb2c2d9f9a30ff">here</a>.</p><p><em>Originally published at </em><a href="https://gist.github.com/misterussell/4eadd04299f8189abebf79569ede9fce"><em>gist.github.com</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d354abd4e2fc" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Optimizing Conway’s Game of Life in JavaScript — Part III]]></title>
            <link>https://medium.com/@MisteRussell/optimizing-conways-game-of-life-in-javascript-part-iii-eca474cc9032?source=rss-5ec3f8b70c39------2</link>
            <guid isPermaLink="false">https://medium.com/p/eca474cc9032</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[es6]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[functional-programming]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Maxwell Russell]]></dc:creator>
            <pubDate>Fri, 19 Jan 2018 19:42:14 GMT</pubDate>
            <atom:updated>2018-01-19T19:42:14.636Z</atom:updated>
            <content:encoded><![CDATA[<p>In <a href="https://medium.com/@MisteRussell/optimizing-conways-game-of-life-in-javascript-part-i-a237039e3d26">Part I</a> and <a href="https://medium.com/@MisteRussell/optimizing-conways-game-of-life-in-javascript-part-ii-8cdbb1a972ab">Part II</a> I worked through the basic logic of analyzing a game of life. I created hash maps to calculate the living state of cells, and set up a toroidal array structure. In this post I will be diving into how I have built a visual structure in React, utilizing state to manage and render each generation of life for a set of cells.</p><h3>Provisioning</h3><p>I used <a href="https://github.com/facebookincubator/create-react-app">Create-React-App</a> as my build tool to jumpstart the project and dive in to coding, in an attempt to minimize the time spent provisioning the project. Switching out my testing utilities to Mocha/Chai added some time to provisioning. You can read about that <a href="https://medium.com/@MisteRussell/testing-with-mocha-chai-in-create-react-app-66ffb2d5c0f7">here</a>.</p><p>I’m utilizing <a href="https://react-bootstrap.github.io/">React-Bootstrap</a> for most of my basic components in this project, primarily because I’m building this into a hub of practice exercises that I can both visualize and test with React. Things like Buttons, Menus, and Modals will all be pulled bootstrapped, with a few minor tweaks to keep them reusable based on the state of the parent container.</p><p>Knowing that I was going to move this to React, I was very mindful when building the initial game logic. I kept everything pretty functional. Functions received their inputs and returned new copies of the data needed, with no side-effects nor mutations to the parent data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*elikPDgZbDlYFg-TLTaEpA.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/photos/OLNG_p0JMao?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Samuel Zeller</a> on <a href="https://unsplash.com/search/photos/pattern?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><h3>Handling Data</h3><p>I considered implementing a state container to manage my data, but settled on having React state be the top level of data. Changes made to the data would be set to the container state and trickle down accordingly. There is one piece of data that I am handling with an outside data-store, which I will discuss briefly.</p><p>The state of my container is handling a few things:</p><ol><li>Conditional aspects for reusable components: Button text, Button callbacks, Modal display and text</li><li>Game related rendering: The dimensions of the CSS Grid Game Board, what Cells are active, what Cells are inactive, the activity state of the game</li><li>Game related data: The initial Seed structure, the hashMap for each generation, and the interval for calculating the next stage of life</li></ol><h3>Simple State Updates</h3><p>For updates to data I am no longer directly updating state with the mutable function of:</p><pre>this.setState({ foo: &#39;bar&#39; });</pre><p>I am in turn, returning full copies of the state that needs mutated. I like this pattern because changes are set to the state on completion, meaning that if I were to call upon a state property after the function is complete, the new state would be registered.</p><pre>this.setState((prevState) =&gt; {<br> let foo = { foo: &#39;newBar&#39; };<br> return { foo }; <br>});</pre><p>Let’s dive into an example of this when a cell is clicked. When a cell is clicked the array that the React component is rendering needs to either a) change the cell colour to active, or b) change it back to inactive. This is handled with inline styling based on the value of the index of the cell array. I immediately return a state change, because clicking a cell doesn’t have any other side-effects.</p><pre>this.setState((prevState) =&gt; {<br> const cellState = prevState.cells[cell] === 0 <br>  ? 1 : 0;<br> const activeCells = prevState.cells[cell] === 0 <br>  ? prevState.activeCells += 1 <br>  : prevState.activeCells -=1; <br> const copy = [...prevState.cells]; <br> copy[cell] = cellState; <br> return { cells: copy, activeCells }; <br>});</pre><ul><li>The first thing that is handled is the new value of the cell. Activity is conditionally set based on the current array value; 0 for empty, 1 for active.</li><li>The next thing that I’m taking into account when clicking a cell is the total number of active cells on the Game Board. If a cell is inactivated, it is removed from this list.</li><li>A mutable copy of the prevState array is then saved so that I can make changes to the array of cells to be updated.</li><li>Finally a new state object that updates cells and activeCells is returned.</li><li>An important detail of this function is that it actually receives an argument cell which is the array value of the cell that was clicked. This is sent through the props to the cell and to this function onClick.</li></ul><p>Handling state in this requires you to be more literal with changes. For example: Let’s say I accidentally sliced some indices from my cells array, if I return only the new array values, the missing values won’t persist in state. I would end up with a new array that would render a Game Board with cells missing.</p><ul><li>Note, this.setState() takes two arguments, the second being currentProps. As my main container has no props related to the game, I&#39;m not including this optional argument.</li></ul><h3>Conditional State Updates</h3><p>Let’s look at a more complicated example, the updateGameBoard() method. This returns conditional state changes. Rather than returning an object with my new changes defined in the return, I&#39;m saving updates to the final state changes in a nextState object. There are two things that need returned for each condition, hashMap and cells, so those are defined at the highest level of the function. Everything is saved in nextState so that needs to go ahead and be defined as well.</p><pre>let hashMap; <br>let cells; <br>let nextState;</pre><p>On the condition that the game has been ended due to no more cells being changed, or because the user has paused the game the current state of the cells is returned.</p><pre>if (prevState.gameState === false) {<br> cells = [...prevState.cells] <br>}</pre><p>If the game is still running each pass of updateGameBoard, which is run every 175 ms, will generate a new hashMap based on the current array&#39;s values. The hashMap generation is pretty clunky, so I may pipe these together later.</p><pre>hashMap = generateNextGenState( <br>           generateGenState( <br>            createHashableArray(<br>             prevState.cells, prevState.totalBound))); <br>cells = [...prevState.cells];</pre><p>Here is where we hit our first hidden side effect. The generateNextGenState function is actually saving any cell whose value has changed into a Store variable defined in a high level module. Since I&#39;m not using a state container tool, I&#39;m reaching out to that in updateGameBoard which seems like a bit of an anti-pattern, but as I&#39;m not returning the changed value from the function, but rather relying on a global variable the function will break if the Store isn&#39;t computed correctly. If I was using a state container, I&#39;d probably throw a listener on the store and have it deal with all the changes and remove my state updaters from the component all together. The snipped that updates the store is pretty simple:</p><pre>if (cell.cellState !== nextState) { Store.changes[cell.arrayPosition] = nextState; <br>}</pre><p>If the Store doesn’t register any changes to the cells, the game is turned off, and the interval that was updated the cells is cleared, and a modal shown to let the user know why the game has paused. There is a bit of a bug here because the modal isn’t shown immediately when the game dies but rather on the pass after the game has died. This lag is noticeable enough to pursue a fix.</p><pre>nextState = { <br> gameState: false,<br> interval: clearInterval(prevState.interval),<br> modal <br>};</pre><p>If the Store does have pending changes then edits are made to the copy of the current cells array. The store is then cleared out for the next pass.</p><pre>Object.keys(Store.changes).forEach(key =&gt; {<br> cells[key] = Store.changes[key];<br>}); <br>Store.changes = {}; <br>nextState = { hashMap, cells };</pre><p>After cycling through each of the conditions setState returns nextState with the appropriate changes to state stored in the new object. It feels so clean!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qn4w7OSeKqSOEBJIljy7xw.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/photos/ok6BBLD3b_0?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Thaï Hamelin</a> on <a href="https://unsplash.com/search/photos/nests?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><h3>Nested Object Property Updates in State</h3><p>One last pattern for the setState() function that I want to mention is that you cannot update certain properties, as would seem logical. I.e:</p><pre>this.setState((prevChanges) =&gt; { <br> return { modal.show: true }; <br>});</pre><p>Single properties cannot be adjusted, most likely because this pattern of updating state requires the complete state of the object to be updated. I’m using the <a href="https://babeljs.io/docs/plugins/transform-object-rest-spread/">babel spread transform</a> to handle this update:</p><pre>this.setState((prevChanges) =&gt; { <br>  let show = true; <br>  let modal = { ...prevState.modal, show }; <br>  return { modal } <br>});</pre><p>By handling the update this way, any of the other properties of the modal state object are saved, like the text that was last generated for the modal. I’m jumping a bit ahead of myself for this, but I’m planning to track the number of times the user has played a dying game, etc…, and will likely need to save this info after each game ends.</p><h3>Conclusion</h3><p>All functions in the <a href="https://github.com/misterussell/practice-hub/blob/master/src/containers/gameOfLife/lifeBoard.js">Game Board container</a> only return updates to state. None have side-effects (beyond the one function that updates the store of pending changes).</p><h3>Next Steps</h3><p>I have some decisions to make for what I handle next.</p><ul><li>When the size of the array is grown, how do I want currently selected cells to be handled? Currently they just keep their index in the array and move due to the shift in columns and rows</li><li>Do I want to implement a state container to get more practice with one of these?</li><li>Should I add transitions to the cells, for pzazz</li><li>How do I want to handle data tracking? Should I build a dash so that the user can see what happened in the game? Would stats be interesting or complicated? (I’m probably going to do this because I’m a data Junkie)</li></ul><p><em>Originally published at </em><a href="https://gist.github.com/misterussell/5084b9cc170f1f21499fab2e780543c1"><em>gist.github.com</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=eca474cc9032" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>