#2 Custom Operators

Imagine if you could add a new operator like a plus(+) or minus(-)?

This is where the custom operator joins the party 🎉!

Depending on the direction I wanted to push the tiles to (left, right, up or down), I had do call the respective transformation functions in a certain order and even chained up, like:

Rotate the matrix Flip the matrix Combine the values Flip back the matrix Rotate back the matrix

The 3 main transformation functions

Since I'm always returning the transformed matrix, the first option I had was to go with the simple "dot notation / concat", like:

rotate(matrix)

.flip(matrix)

.operateRows(matrix)

.flip(matrix)

.rotate(matrix)

Because the logic behind this set of functions is that we are always combining rows to one side, that’s why depending on the direction we’re moving the tiles across the board, we have to manipulate, operate and manipulate it back to the original state.

So at this moment, I realized that I could have a custom operator to help out representing all the transformation chain in a simple way:

By creating the custom operator (|>), I got the ability to represent the chaining of operations in a very "instructional" list, where anyone could read it like a simple set of instructions:

All the directions that we can push the tiles using the custom operator |>

Notice how easy it is to read how the code is transforming the matrix.

Of course, the GameEngine was created fully with Test Driven Development, the main ingredient of my refactoring strategy.

Because I had enough coverage, I had the freedom to experiment a lot of different ways to clean up the code, test out different approaches and so on.

Here are the tests that I used to drive the implementation of the GameEngine:

GameEngine tests

Here's what we have so far:

4x4 Matrix GameEngine responsible for transforming matrices (basic game operations)

So now it is time to talk about dealing with User Interface!