Bombing JavaScript Fatigue with Minesweeper (Part 2 — Reducers)

Part 1 here.

Let’s get straight to business.

Let’s think about all the state we want to manage. I’ll make a checklist:

First things first, I like to note down my action types. And think about these first:

Like the level of difficulty, how many mines are in the grid, and col/rows numbers.

Alright so we save a bunch of meta data we’re interested in. And when the store receives messages corresponding to our difficulty levels, we’ll update our game stats to Easy, Normal or Hard. This will effect the number of mines, and the row/cols we have.

I should probably keep track of adding a flag, and resetting them.

We’ll later right a hook into the UI to update this state as the user places flags on their minesweeper grid.

We’ll later right a hook into the UI to update this state as the user places opens up the bomb-less tiles.

From the docs

The combineReducers helper function turns an object whose values are different reducing functions into a single reducing function you can pass to createStore.

The resulting reducer calls every child reducer, and gathers their results into a single state object. The shape of the state object matches the keys of the passed reducers.

WAIT WAIT WAIT.

Doesn’t the reducer for our Game Time look exactly the same as our Open Tiles reducer?

To dry out our code we should write a “Higher Order Reducer”. When writing these types of reducers, you need to ask yourself, “How would I describe the state change.

For the case of Game Time and Open Tiles, they both can increment and reset. Essentially we have 2 states that increment by one per dispatch, but we need to use these states to power different parts of our application.

Let’s write a HO Reducer:

Now we can have multiple states with the same state shape without duplicating code.

Let’s update our Root Reducer

Now we have described the state of a Minesweeper app! Next we’ll write our api to update this state. We call these Actions.

Part 3 here.

Full code:

This post is part of a series called Mastering Meteor and Redux. You can read the course syllabus here. Follow me on Twitter @abhiaiyer and I’ll see you for the next chapter.

Front-end developer

There frontend developers can share their experience with other developers

31

31 claps
Abhi Aiyer

Written by

Software Engineer at Workpop, Inc.

Front-end developer

There frontend developers can share their experience with other developers