Creative Coding

A Creative Writer's Guide to Code

Custom SQL: Part One

Introduction

Writing custom SQL queries is not something I have to do often, especially when most my database querying can be easily written with Rail’s Active Record library. However, every now and then, whether for performance or just utility, I need to write some custom SQL. Since those times are few and far in-between, I’m going to write a helpful four-part series with the basics: setting up tables, simple queries, aggregate functions, and joining tables. Here we go!

Database Table Basics

A database table looks very similar to an excel spreadsheet. You have rows and columns. Columns contain information about your entries and rows contain each individual entry. Each row should start with a unique ID that we use to identify the entry, called the Primary Key. The primary key is always an integer. There are many other data types available to us, aside from integers, some basic ones are: text, booleans, and dates.

Creating a table

If I wanted to create a table for all the pets my friends and I have, we’d want to have a couple tables. First and owners table that would just have an id, and a name for each person. Second we’d want to have a pets table with the name, age, adoption_date, and friendly columns. Here’s the SQL to create those tables:

The owner’s table:

1
2
3
4
CREATE TABLE owners (
id INTEGER PRIMARY KEY,
name TEXT
);

The pet’s table:

1
2
3
4
5
6
7
CREATE TABLE pets (
id INTEGER PRIMARY KEY,
name TEXT,
age INTEGER,
adoption_date DATE,
friendly BOOLEAN
);

Quick thing to notice is that each command in SQL is concluded with a semi-colon. Let’s add some pets and owners:

The owner’s table:

1
INSERT INTO owners (name) VALUES ('Sammy'), ('Sally'), ('Sarah');

The pet’s table:

1
INSERT INTO pets (name, age, adoption_date, friendly) VALUES ('Spot', 3, 2015-01-15, 'true'), ('Scruffy', 7, 2012-06-01, 'true'), ('Slappy', 2, 2017-01-01, 'false');

Now you’ll notice we haven’t stored any indication of who owns which pet. I could edit pets table to include an owners column like this:

1
ALTER TABLE pets ADD owner_id INTEGER

However, what happens when I want to share a pet with Sally? We can’t have an array of owner ids in the owners column on the pets table. The solution is to create a new table that stores those relationships. Each entry will represent a pet to owner relationship with a primary key, a owner_id column, and a pet_id column. That means that if Sally and I share a pet, there will be an entry for her relationship with the pet and an entry with my relationship with the pet. This is called a join table.

Join table:

1
2
3
4
5
CREATE TABLE owners_pets (
id INTEGER PRIMARY KEY,
owner_id INTEGER,
pet_id INTEGER
);

Now let’s add some relationships:

1
INSERT INTO owners_pets (owner_id, pet_id) VALUES (1, 1)(2, 1)(2, 2)(3, 3);

Conclusion

We’ve built three tables and populated them with some info, all in bespoke, handwritten SQL! Great job. Our next post will deal with querying those tables to get back some information.

The Big O

What is the O?

As a developer working with real world systems, it is not always enough to solve the problem. We need to solve the problem as efficiently as possible. That means reducing the cost of our calculations. In order to think about this, we need some vocabulary, so let’s define our terms.

Cost is being valued in the number of calculations the computer must do in a worst case scenario. This is another way of expressing Time Complexity in computer science. For example, if we have a function that looks at every letter of a string, the cost of the function is equal to the length of the string in the worst case, ie. where the function must go through the entire string before concluding.

That cost in the worst case scenario is called the “Big O”. In the example above, the Big O is represented by O(n) where ‘n’ is the length of the string.

How do we calculate it?

As the complexity of our inputs grow, how many more calculations does the computer have to go through to complete the function in the worst case scenario? That is what we’re looking to calculate. When calculating this, we’re only interested in the exponential growth, since linear or even geometric growth isn’t going to have a large impact on performance.

Mostly, we’re looking for how many times our function will need to loop through our inputs, whether they are arrays, linked lists, hashes or antying else.

Let’s take a couple of simple functions and talk through the Big O.

What are some common examples?

Big O(n)

1
2
3
4
5
6
7
function simpleSearch(target, array)  {
  for(var i = 0; i < array.length; i++) {
    if(target === array[i]){
      return i
    }
  }
}

In the example above, in the worst case scenario our target is the last element in the array. If that were the case, our simpleSearch function would have to go through the entire array one time in order to complete its task. Because of that, the number of potential computations grows proportionally with the length of the array. Hence the Big O is ‘n’.

Big O(n2)

1
2
3
4
5
6
7
8
9
10
11
function sumSearch(target, array)  {
  var sums = []
  for(var i = 0; i < array.length; i++) {
    for(var j = 0; j < array.length; j++) {
      if(i + j === target){
        sums.push([i, j])
      }
    }
  }
  return sums
}

In the example above, our function needs to go through the entire array every time is called. For each number in the array, it then needs to check each number in the array to see if the add up to the target. That nested loop within our loop means that the growth of the calculations necessary to complete the function grow at a rate of ‘n’ * ‘n’ with the growth of the length of the array.

Let’s end with another popular one, a binary search. Keep in mind that one requirement for a binary search is that the array is already sorted.

Big O(log(n))

1
2
3
4
5
6
7
8
9
10
11
12
13
14
function binarySearch(target, array){
  var min = 0
  var max = array.length - 1
  while( min <= max ){
    var guess = Math.floor( (min + max) / 2)
    if(target === array[guess]){
      return guess
    } else if( array[guess] < target ) {
      min = guess + 1
    } else if( array[guess] > target ){
      max = guess - 1
    }
  }
}

In this example, we’re cutting the length of the array in half every time we check the value. So if we have an array with 10 elements, we’re only looking up 4 elements in the worst case scenario. Which means that we’re performing less calculations than the total number elements in the array. That’s pretty cool!

Conclusion

There are lots of ways to solve a problem with code and they are not all equal. After solving the problem you’re working on, spend the time working out the Big O of the method and see if you can come up with something better.

Good luck and happy coding!

How Can I Work With HTML Collections?

What are HTML Collections?

In vanilla javascript, when selecting elements from the DOM, either through document.getElementById, document.getElementsByClassName, document.getElementsByName, document.getElementsByTagName, or document.getElementsByTagNameNS the return value is an HTML collection. This is important because even though it looks like an array, it does not have the same prototypical methods. Also, and more importantly they are live DOM objects, meaning that if you modify them, you are directly modifying the DOM.

What do we get for free?

First off, the ability to modify the DOM directly is very useful but also a great place for bugs to slip in, so be careful in how you use it.

We also get access to one property and a several methods: 1. HTML collections have a ‘length’ property that can be called with collection.length, and it returns the number of elements in the collection. 2. HTML collections have an ‘item()’ method that can be called with collection.item(index number of the item), and it returns the element at that index. If the index doesn’t exist, it will return ‘null’. 3. HTML collections have a ‘namedItem()’ method that can be called with collection.namedItem(id or name), and it returns the element in the collection with the corresponding ‘id’ or if that doesn’t find anything, with the corresponding ‘name.’

What don’t we get for free?

An HTML collection is not an array, and that means we don’t have all the great array methods like, ‘forEach’, ‘map’, ‘filter’, etc. So how do we iterate over the collection?

First, you should know that there was something I didn’t mention in the ‘what do we get for free’ section, we can still use bracket notation to access elements in our collection! What’s the difference between that an the item method? If you try an access an element with an index that doesn’t exist, item() will return null and bracket notation will return undefined.

With bracket notation, we can use a for loop:

1
2
3
for (var i = 0; i < collection.length; i++) {
  /* do something with collection[i] */
}

Alternatively, there is a way to convert a collection to an array, curtesy of harpo on stackoverflow.

with ECMAScript 5.1 and below:

1
var collectionArr = [].slice.call(collection)

with ECMAScript 6 and above:

1
var collectionArr = Array.from(collection)

Now you can operate on each collection element as if it were an element of this new array. You will still modify the DOM when you change these values.

Conclusion

A question that has come up a few times for me while working with vanilla javascript is when to work with an HTML collection as a collection vs. converting it to an array and working with it that way. I think this comes down to two considerations. First, is your goal to modify the DOM for some or all of the elements in the collection? If so, working with it as a collection seems more direct, and might be more efficient, though I haven’t seen a difference in practice. Second, if what you need to do can be accomplished in a simple ‘for loop’, then great, no need to convert it to an array. Otherwise, converting it to an array will probably save more headaches than the line of code necessary to convert it.

Good luck, hope this helps, and happy coding!

Listening to Javascript: Adding Events

Getting good at listening

This seems to keep coming up in code challenges so I wanted to write about it. Usually this is a piece of a larger challenge, but sometimes these questions are really basic. Sometimes these questions get weird, like in a totally real interview I had:

Interviewer: I want a button to create an alert on the screen.
Me: Ok. Does this button submit a form, and is that what the alert is for? Should the alert display a message depending on where the user clicked or the state of the page?
Interviewer: No.
Me: Ok, great. I’ve got my laptop right here, I can do this in the console on a live webpage, maybe wikipedia.
( I’ve already got the wikipedia page for Dolphins open and I’m pressing ‘option’ + ‘command’ + ‘j’ )
Interviewer: No. On paper. And with all the HTML for a webpage, with the header and body information. Me: Ok, ( a little deflated )

So let’s review how to add an event listeners in javascript and see if we can find some more depth here too. Read to the end for some bonus event listener things with React.js.

Adding event listeners

We need a few things in order to add an event listener. First, what do we want to attach the listener to? In vanilla javascript, we can user our document.getElementBy... functions to select a specific tag, class, name, or id. Second, we’ll need to know what kind of event to listen to, ie. a ‘click’, ‘submit’, ‘mouseover’, or something else. There’s a great list of all the events here. Finally, we need a function. In the interview mentioned above, it was a simple alert message, however, we can do a lot here. We can even call named functions. Ok, the real last thing is whether we want our event propagation to capture or bubble, we’ll get into that a bit later.

Ok, we’re ready to start coding this up.

It’s console time

Let’s add some listeners to the wikipedia page for Dolphins, they’re super smart animals and we should be listening to them.

Open up the console and type:

1
document.getElementById('mw-content-text').addEventListener('click', function(){alert('hi')})

Now click any of the interesting dolphin information. Yay, we get an alert with our message.

Note: if we try and remove the event listener with document.getElementById('mw-content-text').removeEventListener('click', function(){alert('hi')}) , that won’t work because the remove event listener method only works with named functions. Our alert function is an anonymous function. But don’t worry! If you want to get rid of that event handler, you just need to refresh the page.

Who’s up first: propagation

If we add the following listeners to our page, what do you think will happen when we click a paragraph?

1
2
3
4
document.getElementById('mw-content-text').addEventListener('click', function(){alert('hi')}, true)
document.getElementsByClassName('mw-body')[0].addEventListener('click', function(){alert('hello')}, true)
document.getElementById('mw-content-text').addEventListener('click', function(){alert('why, hello there')}, false)
document.getElementsByClassName('mw-body')[0].addEventListener('click', function(){alert('salutations')}, false)

When you click you’ll see: 1. ‘hello’ 2. ‘hi’ 3. ‘why, hello there’ 4. ‘salutations’

The reason for this is that events bubble by default, which means we start with the most deeply nested element’s event, and go up the chain from there. When we set the capture variable to ‘true’, we instead start with the outermost DOM element and work our way down. We also see from this experiment that events that are captured take precedent over those that aren’t. You can experiment by implementing these listeners in different orders, but the outcome will be the same.

Alternatives ( and why not to use them )

You can also do this inline in your HTML element with an ‘onclick’ variable set to a function. This is not ideal as it could take your website longer to render, which would negatively impact the user experience.

Alternatively, you can add an inline listener in javascript with:

1
document.getElementById('mw-content-text').onclick = function(){alert('this works!')}

However, this will overwrite any other listeners written this way and this method doesn’t allow you to control the propagation. Bonus question: if you add this to the dolphins page, what will the new order be?

We want to see the HTML

For closure, this is what a simple html page would look like if it just had a button that created an alert:

1
2
3
4
5
6
7
8
9
10
11
12
13
<!doctype html>
<html>
  <head>
    <meta charset="utf-8">
    <title>Code Challenge</title>
  </head>
  <body>
    <button type='btn' id='alert'>Alert Button</button>
  <script>
    document.getElementById('alert').addEventListener('click', function(event) { alert('hello') } )
  </script>
  </body>
</html>

This was pretty basic, but there are much more fun code challenges out there. One I tried recently that was tricky and fun is this one from Trello. Have fun and happy coding.

Dynamic Forms in React: Part 2

Recap of Part 1

In Part 1, we talked about simple forms in React. Namely, we talked about controlling inputs, updating state, and handling submissions. All of that assumes our form is static and we know the shape of our state. ‘Shape’ in this context means the data contained in the state object, the keys, the types of values, etc.

In part two, we’re going to talk about a more complex form. This form needs a way to update itself, and because we want to control the inputs, the form needs a way to update the state. Finally, when we send off our state object to an API, we need to know how to deconstruct that state regardless of how many phases and actions a user added to our form.

Here’s our gif from Part 1 to demonstrate the kind of form interaction we’re going for: Dynamic form gif

Designing the Form UX

When writing code in react, I find it helpful to start with the design I want to implement. Starting from the design makes it really easy for me to think through the components I want to build, now to nest them, and what props they’ll need to work with.

The first part of the form i pretty standard. Each goal should have a title and a description. I find it really helpful to think about the description as the motivation behind the goal. ie. “I want to go to the gym twice a week to get in shape for the summer.” or “I want to go get ready to run a half marathon by September.” I find it’s really helpful to break down big goals into manageable bits of work, and give myself a set amount of time to finish my task. Deadlines are my friend!

This tells me I want a button in my form to add a “phase”. A phase should have a timeframe, a number of days within which I need to complete this task, and a button to create actions. Each time I press this button, I need a new input for a description of an action. So we are creating dynamic inputs inside dynamically created inputs in a form with controlled inputs. That was a pretty scary problem to start with. But I knew my next step and it seemed like a fun thought challenge. How do I model this data?

Modeling the Data

The process of defining my state took a couple iterations to determine the best way to structure my data so it would play nicely with my database and wouldn’t require more looping than necessary. I started with what was going to be static, since that was pretty simple.

1
2
3
4
5
6
  state = {
    title: '',
    description: '',
    repeat: false,
    // Some way to show all our goals
  }

Great that’s three quarters of our state defined! We’re 75% done with this.

We’re going to want to have a list of goals, in order so we know which comes first, second, etc. That means we want an array of goals. Each element of our goal array is going to need a phase length and a list of actions. That means each element of our goal array is going to be an object with two keys, “phase” and “actions”. Actions is going to be a list of descriptions, that sounds like an array.

Writing that out gives us this:

1
2
3
4
5
6
goals: [
  {
    phase: '',
    actions: []
  }
]

When we start filling this up with goals, our state will eventually look like this:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
  state ={
    title: as a string,
    description: as a text area,
    repeat: true of false boolean,
    goals: [
      {
        phase: length as a number,
        actions: [
          description for action 1, description for action 2, etc.
        ]
      },
      {
        phase: length as a number,
        actions: [
          description for action 1, description for action 2, etc.
        ]
      },
      etc.
    ]
  }

Ok, that looks reasonable! Now that we know what we want the state to look like, and how it will be modified at each step of our user’s journey through the form, we can start thinking through the code to make that happen.

Sudo Code for the Form

We’re just going to sudo code this for the blog because the actual code gets very long, and a bit hairy because I decided to put it inside a modal. If you want to check out the actual code, you can find a link to my repo here.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
  <form onSubmit={send our form data to the API}>
    <input type='text' name='title' value={this.state.title} onChange={update the state with this change}/>
    <input type='text' name='description' value={this.state.title} onChange={update the state with this change}/>
    <input type='textArea' name='repeat' value={this.state.description} onChange={update the state with this change}/>
    <input type='checkbox' checked={this.state.repeat} onChange={update the state with this change}/>
    <button type='button' onClick={ call our add phase function }>Add Phase</button>
    <input type='submit' value='submit' name='Create Goal'/>
    < render all the Goal components based on the goals in the state >
  </form>

  addPhaseFunction(){
    copy the state
    add a new element to the goals array with the object we described above
  }

Then we need to import a goal component that maps over each element of the goals array and displays a phase input that is controlled by the value of the phase key in the object of the goals array. We also need to pass that input a function to update the phase in the state on change.

Additionally our goal component needs to show a button similar to the “Add Phase” button, but this one will say Add action. It only needs to update the state by pushing an empty string onto the actions array in the object.

Finally, our goal component needs to map over the action components and display in input for each of them. It then needs to use that element in the actions array to control the state and pass that input a function to update that state.

This should update our state dynamically, add goal objects to our goals array, add action descriptions to the actions array of it’s associated goals in the goals array. Our form component will keep updating every time the state is set by showing the new components with the new buttons and inputs they are mapping over. And Voila, it works!

Conclusion

There are some pretty cool things you can do with react. This form was a really fun challenge, and I’m really proud of what I built and I learned a lot in the process. If you want to check out the app in action, you can find it here hosted on heroku for free, so I apologize for the loading time.

Thanks for checking it out!

Dynamic Forms in React: Part 1, Regular React Forms

What is a Nested Dynamic Form

Sometimes a form needs to expect the unexpected. When that happens, when the user needs freedom and flexibility, old-school forms just wont cut it. For Habits, I wanted to give the user the ability to add as many fields to the form as they needed to express their goal.

Habits is an activity tracking app that is part accountability through gamificaiton, part exploration of the quantified self, and part guided self betterment. When using the Goal creation form, users are encouraged to give their goal a name, as well as a brief description or motivational sentence. Then, users are asked to divide their goal into smaller, more manageable chunks, divided into phases of time, and each phase is comprised of various actions. When the goal is created, the user’s inputs are translated into a card that allows them to check off what they’ve accomplished toward their goal, divides up the work according to their schedule, and gives them insights into their progress.

In order to cover all that, our form needs to be very special. This is what it’s going to look like:

Dynamic form gif

But we won’t get to that in this post. In this post, we will go through the basics of React forms to get us up to speed for what’s coming in our next post.

Standard Javascript Forms

Let’s build a simple from to accept a ‘name’ input from the user and send if off to our database, in vanilla Javascript. Here’s what our form would look like.

1
2
3
4
<form id="goal-form">
  <input type="text" id="name" name="name" />  
  <input type="submit" value="submit">
</form>

Next we need to create an event handler on window.load to listen for the submit event and hanle sending our information to the api.

1
2
3
4
5
6
7
8
document.querySelector("#goal-form").addEventListener("submit", function(e){
    e.preventDefault()    
    // stop the form from submitting and refreshing the page
    // you can add some validations here
    var name = document.getElementById('name').value
    return createGoal(name)
    // calling some function that sends a post request to our api with the value of the name input.    
})

That’s one way to do things in vanilla Javascript. It’s messy, slow, and not very efficient. Things can get even crazier when there are lots of elements on your page. Searching through all those DOM nodes can get expensive. And when we want to do something dynamic in our form, like in the example above, this process can get very complicated very quickly. React gives us a better way.

Controlled inputs

In React, we try and stay away from the DOM, and use the virtual DOM instead. This means that when we go and look at what the user entered in our form, instead of checking for the form input values in the DOM, we store it in temporary memory, in the React component’s state, and just grab it from there when we’re ready.

Our React state for a name input looks like this:

1
2
3
4
5
6
7
8
9
10
...
export default class GoalForm extends Component {
  constructor(){
    super()
    this.state = {
      name: ''
    }
  }
}
...

All this does is create a GoalForm class component in React with a state object that has a value of ‘name’, which points to an empty string.

Instead of having the React component store the information of the user’s input and have the user’s input be stored in the DOM, which would break the single source of truth convention, we just have the component’s value display the state. That is called a controlled input.

Our form looks like this:

1
2
3
4
<form onSubmit={this.handleSubmit.bind(this)}>
  <input label='name' type='text' value={this.state.name} onChange={this.handleChange.bind(this)} />
  <input type='submit' value='submit' />
</form>

This form has one text input field for a name, that shows the value of the name object in the component’s state. When a user enters something in the input field, that input is intercepted by our handleChange function, which updates the state, the Component is re-rendered, and the new state is shown as the value.

Handling Changes and form Submission

Our handleSubmit and handleChange functions look like this:

1
2
3
4
5
6
7
8
9
10
11
12
handleSubmit(e){
  e.preventDefault()
  this.props.createGoal(this.state.name)
  // this is a function passed down from another component via props. In this case, it will send a post request to an api with the 'name' the user entered.
  this.setState({name: ''})
  // this.setState is a React function that sets the state of the current component to the argument that is passed in and it also forces the component to re-render.
}

handleChange(e){
  e.preventDefault()
  this.setState({name: e.target.value })
}

Conclusion

This is a lot to wrap your head around, controlled inputs, preventing a lot of default actions, completely sidestepping the DOM! I know, it’s a lot. But it’s about to get crazier. In part two, we’ll discuss how to give the user the ability to dynamically add inputs in this controlled system. Stay tuned for Part II.

Building a Game: Generate Unique and Random X and Y Coordinates

Why would I need some random coordinates?

I want to build a game. This game is going to have a dungeon, represented by tiles on a game board, and it will be randomly populated with a door, a key, a bunch of monsters and the player’s starting position. My database schema is expecting an ‘x’ and ‘y’ coordinates for each of these, but to make my game work, I need to make sure that none of these start off on the same square. It wouldn’t be very challenging if the key and door could appear on the same spot. It wouldn’t be fun if the player spawned on the same tile as a monster and lost the game immediately! There are lots of reasons you might want to generate a number of unique ‘x’ and ‘y’ coordinates for a grid of a given size, this would work for all of them.

What do I want my result to look like?

We’re going to start simple and build out more complexity as we get things working. As I said, I need a coordinate for the door, a key, the player and some monsters, that’s a minimum of four coordinates and we need a board that is two squares by two squares to fit everything. In this case, I’m using all the possible coordinates, so I want my final outcome to look something like this hash of info:

1
2
3
4
5
6
7
8
game_coordinates = {
  player: {x: 1, y: 1},
  door: {x:1, y:2},
  key: {x:2, y:1},
  monster: [
  {x: 2, y: 2}
  ]
}

Let’s zoom in on the first problem we want to solve. Getting ourselves the list of unique ‘x’ and ‘y’ coordinates. This sounds like we want to use an array, which we would ultimately need to iterate over to assign values. For now, our array should look like this:

1
unique_coordinates = [[1,1], [1,2], [2,1], [2,2]]

We will use this array later to assign the coordinates to the door, key, player, and monster. Let’s break down what we are seeing. This isn’t one simple array, it’s an array of arrays. Each of the nested arrays represents a unique set of ‘x’ and ‘y’ coordinates. We can also have two arrays for the x and the y values:

1
2
x_values = [1, 1, 2, 2]
y_values = [1, 1, 2, 2]

If we look a little closer, the arrays shouldn’t both be in order like that. In our unique_coordinates array, they ‘x’ values repeat then increment while the ‘y’ values increment then repeat. So we want values that look like this:

1
2
x_values = [1, 1, 2, 2]
y_values = [1, 2, 1, 2]

Let’s hard code this to get started

Now that we have the basic building blocks for our data structure, let’s put it together assuming we have the unique values we need. In our two by two grid, with the x_values and y_values arrays, all we need to do is a simple loop to get our unique_coordinates array, and pull off four coordinates at random:

1
2
3
4
5
unique_coordinates_generator =
x_values.each_with_index.map do |x, index|
  [x, y_values[index]]
end.sample(4)
# >>> [[1,1], [1,2], [2,1], [2,2]]

Perfect! Just note that if you’re following along, your coordinates may be in a different order, that’s exactly what we want. They should all be unique.

To assign each of these to our game board objects, we can do this by assigning each a value from the unique_coordinates_generator. This isn’t the prettiest way to do this, but it will work.

1
2
3
4
player = unique_coordinates_generator[0]
door = unique_coordinates_generator[1]
key = unique_coordinates_generator[2]
monsters = [ unique_coordinates_generator[3] ]

this looks great. The next step is to abstract this to handle grids of any size, with more than four coordinates to accommodate multiple monsters.

Abstraction

To state our problem here more simply, we want to create our x_values and y_values arrays for grids larger than two by two. That means, the size of the grid would need to be an argument. Additionally we can infer from the fact that we need to accommodate a variable number of monsters that the number of monsters will also be an argument. So the skeleton of our code should look something like this:

1
2
3
4
5
6
7
def coord_generator(grid_size, number_of_monsters)
  # some code that creates:
  # x values from 1 to the grid size, where we get a 1 the grid_size number of times, followed by a 2 the grid_size number of times, etc.
  # y values that count from 1 to the grid_size number for the grid_size number of times.
  # then we map over the arrays like we did before.
  # finally we sample the array with the number of monsters plus the door, key, and player.
end

Now that we’ve stubbed that out in sudo code. It is really easy to translate that to code using some simple ruby operators:

1
2
3
4
5
6
7
8
def coord_generator(grid_size, number_of_monsters)
    x_values = ((1..grid_size).to_a * grid_size).sort()
    y_values = ((1..grid_size).to_a * grid_size)
    unique_coordinates = x_values.each_with_index.map do |x, index|
      [x, y_values[index]]
    end
    unique_coordinates.sample(number_of_monsters + 3)
  end

Conclusion

We’ve almost finished, but we still have one thing left to do, we need to output our game_coordinates object. To do that, we need to assign the values like we demonstrated above, but we also need to account for having several monsters.

1
2
3
4
5
6
7
8
9
10
11
12
13
def game_coordinates(grid_size, number_of_monsters)
  unique_coordinates = coord_generator(grid_size, number_of_monsters)
  player = unique_coordinates[0]
  door = unique_coordinates[1]
  key = unique_coordinates[2]
  monsters = []
  number_of_monsters.times do |i|
     monsters << unique_coordinates[ 3 + i]
  end
  game_coords = {player: {x: player[0], y: player[1]}, door: {x: door[0], y: door[1]}, key: {x: key[0], y: key[1]}, monsters: monsters.map do |monster|
    [x: monster[0], y: monster[1]]
  end}
end

When we call this method with a grid size of two and one monster, we get the results:

 {
   :player=>{:x=>2, :y=>1},
   :door=>{:x=>1, :y=>1},
   :key=>{:x=>2, :y=>2},
   :monsters=>[[{:x=>1, :y=>2}]]
   }```

When we call this method with a grid size of four and three monsters, we get the results:

{ :player=>{:x=>2, :y=>1}, :door=>{:x=>4, :y=>3}, :key=>{:x=>4, :y=>2}, :monsters=>[ [{:x=>1, :y=>3}], [{:x=>3, :y=>4}], [{:x=>4, :y=>1}]] } ```

We’ve done it! We started with a scary sounding requirement, “generate a number of random and unique ‘x’ and ‘y’ coordinates for a grid of a given size.” We brainstormed about how we wanted the data to look and we divided it into simpler and simpler parts. We broke that down into basic procedural tasks with a hard coded example. Then we abstracted away each of the hard coded parts with information from the requirements, until we produced a general and powerful piece of code.

Good luck and happy coding!

React Containers and Components: Classes vs Functions

What is Refactoring?

First, a quick note on refactoring code for those new to the idea. Lot’s of different configurations and styles of code will get the job done. Refactoring is about organizing and cleaning up your code for a few reasons.

First is readability. If someone else is going to work on something you built, you want to give them an easy way to understand what is going on. Not to mention, if you want to pick up an old codebase after a few months, you want to leave yourself a nice rode map to what things are doing and where. Refactoring your code will help keep concerns separate and will tell you exactly where to look to find each piece of functionality.

Second is optimization. This is a bit trickier and has less to do with organization and naming conventions and more to do with an understanding of which operations and methods are more costly to perform than others. There are a lot of great resources on this, but we’re going to stick with the readability side of refactoring for this post.

What is Component Design?

When deep into a code project, I can get tunnel vision on the tasks I’m trying to solve. I’m deep into a file, I know exactly where everything is and how it all interacts. But when I come back to that document a day later, it just looks like a mess. If a bug creeps in, I’m helpless. The component container design pattern is a really helpful way to organize React code. There are a few simple rule of thumb which we will demo in the rest of the post. Simply put, Containers are responsible for fetching data, keeping state and behavior, and passing the relevant bits of info down to its children. Components are ideally simple functions that receive props from their parent container and render HTML as JSX.

Let’s Build a Simple App in One Messy Place

To demo this idea, we’re going to build a very simple PetBook app with three pieces. First there is a simple nav bar with our Logo. Second there is a form to add animal names. Third, there is a list of the animals we’ve entered. The App will work like this:

PetBook demo gif

We’re using three files to build PetBook: index.html, index.js, and app.js. We’re also using Materialize CSS for some styling. Let’s take a look at our index.html page:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>React Intro</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.98.2/css/materialize.min.css">
  </head>
  <body>

    <div id="container" class="container"></div>

    <script type="text/javascript" src='bundle.js'></script>
  </body>
</html>

It’s super short and sweet. We’re bundling our files using webpacks to make development iterations quick and painless. Otherwise, our entire app is being rendered in the container div. Next, let’s take a look at index.js:

1
2
3
4
import React from 'react'
import ReactDOM from 'react-dom'
import App from './App'
ReactDOM.render(< App />, document.getElementById('container'))

Another super short and sweet file. All this is doing is requiring react and react-dom and rendering the app to the index.html page by attaching its contents to the div with the id of ‘container.’ Finally, let’s take a look at where all the magic is happening. Our colossal App.js file:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
import React, {Component} from 'react'
export default class App extends Component {
  constructor() {
    super()
    this.state = {
      input: '',
      animals: []
    }
  }

  handleChange(e){
    this.setState({
      input: e.target.value
    })
  }

  handleSubmit(e) {
    e.preventDefault()
    this.setState({
      animals: [...this.state.animals, this.state.input]
    })
    this.setState({
      input: ''
    })
  }

  render() {
    return (
      <div className='zoobook'>

        <nav>
          <div className='nav-wrapper'>
            <a className='brand-logo'>
              PetBook
            </a>
          </div>
        </nav>
        <div className="row">
          <div className="col s6">
            <div className={'zoo-form'}>
              <h3>Add a Pet</h3>
              <form onSubmit={this.handleSubmit.bind(this)}>
                <label>
                  Animal Name:
                  <input type='text' value={this.state.input} onChange={this.handleChange.bind(this)}/>
                </label>
                <input className="waves-effect waves-light btn" type='submit' value='Create Animal'/>
              </form>
            </div>
          </div>

          <div className="col s6">
            <div className='zoo-list'>
              <h3>Your Pets</h3>
              <ul>
                {this.state.animals.map(function(animal) {return <div className="card-panel" key={animal}>{animal}</div>})}
              </ul>
            </div>
          </div>

        </div>

      </div>
    )
  }
}

This file is huge. Especially for such a simple app! This will get very tricky to debug or to add to in a hurry, not to mention, working on this file will wear out your mouse’s scroll wheel really quickly. Looking at the working app, it’s pretty easy to see that there are three things going on. First, there’s the nav bar. Second is the form for entering animal names. Last is the Pet list. I wonder if there’s a way to organize this. There totally is!

Separating Concerns Out Nicely

Using our guidelines from before, we can say that the form is the only part of our app responsible for creating and handling data, so that will be a stateful component. Everything else can be a functional, or presentational container. We’re going to organize all this into a folder called ‘src’. Don’t forget to update any dependencies in your application to account for the path changes. The App.js file now lives in our containers folder and is only responsible for rendering the nav bar and the Pet Form container. It now looks like this:

1
2
3
4
5
6
7
8
9
10
11
12
import React, {Component} from 'react'
import NavBar from './NavBar'
import PetFormContainer from '../containers/PetFormContainer'
function App() {
  return (
    <div className='zoobook'>
      <NavBar />
      <PetFormContainer />
    </div>
  )
}
export default App

Short and sweet! Next is our nav bar component. The job of our nav bar is only to render the nav bar. Pretty straight forward, right! In the future. If we want to add more pages to this application, we can include this nav bar container and keep any changes consistent across our entire app just by updating this file. Here it is:

1
2
3
4
5
6
7
8
9
10
11
12
13
import React from 'react'
function NavBar() {
  return (
    <nav>
      <div className='nav-wrapper'>
        <a className='brand-logo'>
          PetBook
        </a>
      </div>
    </nav>
  )
}
export default NavBar

This is looking great so far, but we haven’t gotten to the meat and potatoes of our petbook app yet. Here is our Pet Form container it is a stateful classical container that inherits from the react compnent library. It’s responsible for controlling the user input, maintaining a list of the user’s pets in an animals array, and it is able to add a new animal from the form to the animals array and rerender the Pet List component to display the changes. Here it is:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
import React, {Component} from 'react'
import PetList from '../components/PetList'
export default class PetFormContainer extends Component {
  constructor() {
    super()
    this.state = {
      input: '',
      animals: []
    }
  }
  handleChange(e){
    this.setState({
      input: e.target.value
    })
  }
  handleSubmit(e) {
    e.preventDefault()
    this.setState({
      animals: [...this.state.animals, this.state.input]
    })
    this.setState({
      input: ''
    })
  }
  render() {
    return (
      <div className="row">
        <div className="col s6">
          <div className={'zoo-form'}>
            <h3>Add a Pet</h3>
            <form onSubmit={this.handleSubmit.bind(this)}>
              <label>
                Animal Name:
                <input type='text' value={this.state.input} onChange={this.handleChange.bind(this)}/>
              </label>
              <input className="waves-effect waves-light btn" type='submit' value='Create Animal'/>
            </form>
          </div>
        </div>
        <PetList animals={this.state.animals}/>
      </div>
    )
  }
}

A lot of this should look familiar from our original App.js file. This is the longest file in our new design pattern, but it is much simpler than our original App file. It is only responsible for maintaining the state, keeping an eye on the form, and sending along any new info to the Pet List component. Here’s that final component:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
import React from 'react'
function PetList( props ) {
  return (
    <div className="col s6">
      <div className='zoo-list'>
        <h3>Your Pets</h3>
        <ul>
          {props.animals.map(function(animal) {return <div className="card-panel" key={animal}>{animal}</div>})}
        </ul>
      </div>
    </div>
  )
}
export default PetList

The only difference here is that the Pet List component is getting the animals array passed from the Pet Form container as a prop.

Conclusion

That’s it. Our singe file app has been successfully refactored into a component and container design pattern. It will make expansion of our app much simpler by modularizing the responsibilities. It will also make the app much easier to maintain since we know exactly where to go if anything breaks. No more long scrolling sessions, straining our eyes to find a section of our app file. Happy coding!

Create a Quick TDD Environment for Javascript

Getting started

Our goal is to get a project up and running quickly. If you haven’t done this before, first we want to create a project directory, create a github repository, and then link the two. Here are the basic steps:

  1. Navigate to your development folder in Terminal.
  2. Type mkdir "project-name" in terminal to create a project folder.
  3. Type cd "project-name" in Terminal to navigate into your project directory.
  4. Type git init in Terminal to set up your directory as a git repository.
  5. Create a readme file by typing touch README.md in Terminal.
  6. Add and commit your new repository by typing git add . and git commit -m "first commit".
  7. To create a github repository, login to github in your browser and navigate to github/new to create a new repository.
  8. Once there, give your repository a name, use the same one as your project directory, and leave the “Initialize this repository with a README” option unchecked.
  9. Click “Create Repository”.
  10. Back in Terminal, type git remote add origin git@github.com:your-git-username/your-repository-name.git to set up the connection between the folder on your computer, and the repository in github.
  11. Then type git push -u origin master to push the files, ie. your readme, from your project folder to github.

Now that your project is up and running, it’s time to create a testing environment.

Jasmine versus Mocha

There are two very popular testing libraries for Javascript, Jasmine and Mocha. Both are great, and weighing the pros and cons of each is enough for another blog post. Some people have already written great articles on the topic here:

  1. Kevin Groat
  2. Marco Franssen

I’m more familiar with Mocha, so we’re going to go with that.

Setting up Mocha

First we need to create our NPM dependencies, with a package.json file. There is a great walkthrough built in for us by typing npm init in Terminal. Just follow the promts and include a name, repo, and some other metadata in the form. That will create a package.json file in your project folder. Don’t forget to add/commit your changes frequently.

Create a mocha dependency in your project package.json file by typing npm install --save mocha in Terminal. Create a test file with atom test/test.js. I’m using Atom, but you can replace that with your editor of choice.

This is where it can get pretty hairy. There is a lot to install to get up and running. I would advise starting off with a simple test and some simple code just to have something to test against. We also need to require the files with our code and assign it to a variable, as well as require any other mocha assertion libraries you want to use. My basic test.js setup looks like this:

In test.js:

1
2
3
4
5
6
7
8
9
10
var expect = require('expect.js');
var myCode = require('../index.js')

describe ('test', function() {
  it('returns "Hello, world!" as a string', function() {
    expect(myCode.test()).to.be("Hello, world!")
  })
})

## All other tests below

In terminal: npm install --save expect.js

Now we’re ready to start writing our functions. If you want to build out this application, you can move all your inclusions and exporting responsibilities to a root.js file in your test folder. That will allow you to write your functions normally and branch out to other .js files without things getting to messy. But more on that in another blog.

to pass our first test, add the following code to index.js:

1
2
3
var test = function() {
  return "Hello, world!"
}

But we’re still not passing our test yet. With mocha, it’s not enough to just include it in the test.js file, we need to export them from our index.js file as well. We do this with some general code at the bottom of our file that we update with each additional function. Here’s what we need at the bottom of index.js to export our first test:

1
2
3
if(typeof exports !== 'undefined') {
    exports.test = test
}

Now you should be passing your first test. Hurray! Now that you’re up and running. The mocha documentation on how to write more complex tests is a great resource.

Bonus

You don’t need to export every function in your index.js file. You only need to export the functions that your tests will call on. So if you have a function called testTwo that should accept two arguments, multiply them, and return the result, you can export it in your exports like exports.testTwo = testTwo. However, if that function just returns a helper function, called multiplier(num1, num2), you would not need to export that function as well.

Here’s what this test looks like in test.js:

1
2
3
4
5
describe ('test2', function() {
  it('multiplies two numbers together', function() {
    expect(myCode.testTwo(3, 5)).to.be(15)
  })
})

And here is how you would pass it in index.js. Note that you do not need to export multiplier.

1
2
3
4
5
6
7
8
9
10
11
12
var testTwo = function(num1, num2) {
  return mulitplier(num1, num2)
}

var mulitplier = function(a, b) {
  return a * b
}

if(typeof exports !== 'undefined') {
    exports.test = test;
    exports.testTwo = testTwo
}

Special thanks to JJ for guiding me through this process!

Bringing Terminal Applications to Life: CLI Animations With Ruby

Animation in the Terminal?!

While working on a command line application, with Scott Harrison, we decided to add some flair with an animation in the terminal. While looking for inspiration, and to see if it is even possible, we found this amazing, and very long example. Just type telnet towel.blinkenlights.nl into your terminal to connect with a telnet server that broadcasts Star Wars Episode IV!

The project we were working on was pulling data from NYC Open Data, specifically from the database for free public wifi locations, and using a google maps gem for rails, called geocoder, to help find the closest free wifi access point. While looking for a suitable animation, we found this on gify, and we knew we had to make it happen.

Wifi clip from GIPHY

Aside for the fun of it, why would you want to run an animation in a terminal application? We found our application hit some delays when looking for the user’s IP address and while hitting the google maps api. A neat animation works as a loading screen, while that happens in the background. That isn’t what we did, but that would be a great project for refactoring.

The plan

Here’s a checklist; we’ll go into detail below:

  1. Find a clip
  2. Extract individual frames
  3. Convert each frame to ASCII
  4. Add the folder with your slides to your project
  5. Build an iterator method to loop through the frames

Building your files

First, you’ll need a clip that you want to animate, it can be saved as a gif, or even in a video format. We downloaded ours from the link above and it is formatted as an mp4 file. Then, you’ll need to extract the frames from your clip. There is a nifty terminal tool to do this, called ffmpeg, that you can read more about. You’ll need to make some decisions about where to start stop and stop your extraction, and many frames you want per second. Our command looked something like this: ffmpeg -i wifinder_animation.mov -r 5 image-%02d.jpeg.

After that it gets a bit tedious, you have to convert each image to ASCII art. Thankfully there are lots of free tools online that will do this for you. If we were dealing with a longer clip, we would have looked for a way to convert the entire folder in one go, but we just uploaded each frame to this site. Pro tip: name your files based on where you want your clip to start and stop, starting with something like “1” and counting up, so you can easily iterate through the images.

Then just add the folder with your beautiful ASCII art frames to your repo and get ready to build an animation!

Building an animation

To get started, we’re going to write an animation method that will loop through our images in the animation folder one time.

1
2
3
4
5
6
7
8
9
def animation
  i = 1
  while i < 60
    print "\033[2J"
    File.foreach("ascii_animation/#{i}.rb") { |f| puts f }
    sleep(0.03)
    i += 1
  end
end

First create a variable and set it to 1, then we’ll start our iteration. For a 60 frame animation, we’ll run our loop while our variable is less than 60. Then we’ll clear the window by moving the cursor to the top right of the terminal window with print "\033[2J". Then we’ll loop through our animation folder, named “ascii_animation” in this example, using our variable to indicate the file name, 1.rb, 2.rb, 3.rb, etc, printing each line of our image to the terminal. Then we’ll let the image stay on screen for .03 seconds ‘sleep(0.03)’. Finally we’ll increment our iterator and begin the loop again.

If we want to run our animation multiple times, we can just put a loop method before our method call, like this: 3.times { animation }

Finally, if you want to freeze frame your animation somewhere in the middle, instead of the potentially boring last frame in your file, you can start another loop, this time ending at your target frame.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
def animation_with_a_great_final_frame
  2.times do
    i = 1
    while i < 60
      print "\033[2J"
      File.foreach("ascii_animation/#{i}.rb") { |f| puts f }
      sleep(0.03)
      i += 1
    end
  end
  i = 1
  while i < 30
    print "\033[2J"
    File.foreach("ascii_animation/#{i}.rb") { |f| puts f }
    sleep(0.03)
    i += 1
  end
end

That’s it! Now you can enjoy our sweet CLI wifi animation.

Showtime!

WiFinder gif