cover-img

How to Create a Wordle with TDD in Javascript

We keep practicing this amazing Kata and learning. You can follow the steps!

13 September, 2022

12

12

2

TL;DR: Javascript is also awesome for TDD

During January 2022 Wordle rush, I wrote an article describing how to create a Wordle with TDD using PHP.
A few months after, I transcribed the UI version of a Wordle created with Codex Artificial Intelligence.
I will combine both worlds to program as a Centaur.
I will also compare the process and output from different language versions.
This is the Javascript version.

Set-Up

As usual, we will focus on the game business logic, knowing we can build the user interface with natural language commands.
In this article, I will use a repl.it with Jest.
Javascript has many Unit testing frameworks.
You can use whatever you like.
Let's begin…

Defining a Word

Following the same principles as the previous article, we will start by defining a Wordle Word.
The smallest information amount in Wordle is a word.
We can argue that letter is smaller, but all needed letter protocol is already defined (we might be wrong).
A word is not a char(5).
A word is not an array.
A word is not a string.
This is a common mistake and a bijection violation.
A word and a string have different responsibilities, though they might intersect.

Mixing (accidental) implementation details with (essential) behavior is a widespread mistake.

So we need to define what is a word.
A word in Wordle is a valid 5-letter word.
Let's start with our happy path:
We assert that prompting for letters in 'valid' returns an array of the letters.
This is the result:
This is fine since we haven't defined what a word is.

Notice

This is a TDD Pattern.

We name the objects following their behavior even before they exist.

Word class is not defined yet.

Our Word's first trivial responsibility is to answer its letters.

This is not a getter. Every wordle word must answer its letters.

We don't care about letter sorting. That would be a premature optimization and gold plating scenario.

We start with a simple example. No duplicated.

We don't mess with word validation yet (the word might be XXXXX).

We can start with a simpler test validating the word is created. This would violate the test structure that always requires an assertion.

The expected value should always be the first in the assertion.

Creating a Word

We need to create a Word with the letters() function.

Notice

We don't need constructors (yet).

We hardcode letters function since this is the simplest possible solution up to now.

Fake it till we make it.
We run all the tests (just 1) and we are OK.

Few Letters

Let's write another test:
The test fails as expected…

Notice

The first test passed

The second test is expected to throw an exception. Which it didn't.

We just declare a generic exception will be raised.

We just raise a generic Error.

Creating special exceptions is a code smell that pollutes namespaces. (unless we catch it, but this is not happening right now).

Changing the current implementation

We need to change our implementation to make test02 pass (and also test01).
And the tests pass.

Notice

We are not using the constructor argument to set up the actual letters (yet).

We just check for a few letters. Not for too many since we don't have yet a covering test.

TDD requires full coverage. Adding another check without a test is a technique violation.

Checking Too Many Letters

Let's check for too many.
We run them:
We add the validation:
And all tests passed.

Refactor (or not)

We can now make an (optional) refactor and change the function to assert a range instead of two boundaries. We decide to leave it this way since it is more declarative.
We can also add a test for zero words following the Zombie methodology.
Let's do it.
It is no surprise the test passes since we already have a test covering this scenario.
As this test adds no value, we should remove it.

Valid Letters

Let's check now what are valid letters:
… and the test is broken since no assertion is raised.
We need to correct the code…
And all tests pass since we are clearly hardcoding.

Notice

We hardcode the asterisc to be the only invalid character (as far as we know).

We can place the checking code before or after the previous validations. -- Until we have an invalid case (with invalid characters and invalid length) we cannot assume the expected behavior.

More Invalid

Let's add more invalid letters and correct the code.

Notice

We didn't write a more generic function (yet) since we cannot correct tests and refactor at the same time (the technique forbids us).

Refactor

All the tests are ok.
We can refactor.
We replace the last two sentences.

Notice

We can refactor only if we don't change the tests at the same time.

The assertion checks only for uppercase letters. Since we are dealing with these examples up to now.

We defer design decisions as much as possible.

We defined a regular expression based on English Letters. We are pretty sure it won't accept Spanish (ñ), German(ë), etc.
As a checkpoint, we have only five letter words from now on.
Lets assert on letters() function.
We left it hard coded.
TDD Opens many paths.
We need to keep track of all of them until we open new ones.

Comparing Words

We need to compare words.
And the test fails.
Let's use the parameter we are sending to them.

Notice

We store the letters and this is enough for object comparison (it might depend on the language).

letters() function is still hardcoded

More Words

We add a different word for letters comparison.
Remember letters() function was hardcoded until now.
And the test fails as expected.

Notice

It is very important to check for equality/inequality instead of assertTrue() since many IDEs open a comparison tool based on the objects.

This is another reason to use IDEs and never text editors.

Let's change the letters() function since we've been faking it.

Comparing different cases

We need to make sure comparisons are not case-sensitive.
Test fails.
We need to take a decision.
We decide all our domains will be lowercase.
We will not allow uppercase letters despite the UI having caps.
We won't do magic conversions.
We change the test to catch invalid uppercase letters and fix them.

English Dictionary

Our words are in a bijection with English Wordle words. or not?
Let's try a non-English word.
This test fails.
We are not catching invalid English 5-letter words.

Notice

We need to make a decision. According to our bijection, there's an external dictionary asserting valid words.

We can validate with the dictionary upon word creation. But we want the dictionary to store valid wordle words. No strings.

It is an egg-chicken problem.

We decide to deal with invalid words in the dictionary and not the Wordle word.

We remove the test.

We will find a better way in a few moments.

Wordle Game

Let's create the game.
We start talking about a game that does not exist.
Test fails.
We need to create the class and the function.

Creating Game Objects

Words Attempted

We implement words attempted.
And the simplest solution.
Hardcoding as always.

Start guessing

Notice

We store the attempts locally and add the attempt and also change wordsAttempted() real implementation.

Has Lost

We can implement hasLost() if it misses 6 attempts.
With the simplest implementation as usual.

Notice

We are learning the rules as our model grows.

We lose the game

As always. We stop faking it and decide to make it.

We Play by the Dictionary

We have most of the mechanics.
Let's add valid words dictionary and play invalid.
The test fails as expected.
We fix it.
and the test is fixed, but…

Notice

test13, test14, and test15 were previously working.

Now, they are broken since we added a new business rule.

We need to pass the dictionary when creating the game.

We fix the three of them by adding an array with the words we will use.

It is a good sign our setup gets complex to keep creating valid scenarios.

Play to Win

Now, we play to win.
We add the test and need to change hasWon() accordingly.

Notice

We use no flags to check if someone has won. We can directly check it.

We don't care if it has won in a previous attempt.

We make an addParameter refactor with this new element to previous game definitions.

Correct Word

We added the Correct Word.
We need to assert this word is in the dictionary.

Notice

We needed to change all previous games since we needed to pass the winner game before the start

This is a good side effect since it favors complete and immutable objects.

Lost, Won, both?

What happens if we win in the final attempt?
Zombies ask us always to check for (B)boundaries where bugs hide.
We have all the mechanics.

Letter Positions

Let's add the letter's positions.
We can do it in Word class.
As usual, we get an undefined function error:
Let's fake it as usual.

Notice

Names are always very important.

We can name the parameter anotherWord.

We prefer correctWord.

We are aware we will soon need a complicated algorithm and roles should be clear and contextual.

Match

Let's match
Fails.
We need to define it better
This is a good enough algorithm.
Ugly and imperative
We will refactor it later, for sure.
And all the tests pass.

Notice

The matching property is not symmetric

Incorrect Positions

Now we need the final steps.
Matching in incorrect positions.
and always the simplest solution…

Notice

By adding these safe, zero cases we miss many usual bugs.
A more spicy test case.
Let's go for the implementation
That's it.
We have implemented a very small model with all meaningful rules.

Playing with real examples

img
img

(You will find more daily examples in the repo)

Playing by the complex rules

Playing by the complex rules
I was very happy with my working wordle.
Then I read about its complex rules
Learning new rules is not a problem when we have TDD.
Let's cover the examples from the article
Let's steal the algorithm from the article.
We need to add another function (which will be useful for keyboard colors).

Notice

The algorithm changes a copy of the correct word by placing '*' when the correct position matches

It also hides the visited letters by changing to a special (an invalid '+').

Conclusions

This solution is different and more complete than the previous one.
The wordle rules have not changed.
According to David Farley, we need to be experts at learning.
And we learn by practicing katas like this one.
We end up with 2 compact classes where we defined our business model.
This small model has a real 1:1 bijection in the MAPPER to the real world.
It is ready to evolve.
This game is a metaphor for real software engineering.
Hope you find it interesting and follow the kata with me.

Try it out!

You can play around with the working repl.it.

Next Steps

Combine this solution with the AI-Generated

Use a real dictionary

Change the language and alphabet

Change the rules to a different wordle

Languages
JavaScript

JavaScript

javascript

refactoring

tdd

12

12

2

javascript

refactoring

tdd

Maxi Contieri

Buenos Aires, Argentina

🎓Learn something new every day.📆 💻CS software engineer 👷coding👨🏽‍🏫teaching ✍🏾writing 🎨Software Design 🏢SOLID 🌉TDD 👴Legacy 💩Code Smells

More Articles

Showwcase is a professional tech network with over 0 users from over 150 countries. We assist tech professionals in showcasing their unique skills through dedicated profiles and connect them with top global companies for career opportunities.

© Copyright 2024. Showcase Creators Inc. All rights reserved.