Good vs Evil

Marcos Lipic
3 min readJan 8, 2021

Today we are going to tackle a Lord of the Rings themed CodeWars kata called Good vs Evil. So get ready to be transported to Middle Earth and witness the epic battles between the forces of good and evil.

The challenge is to determine which side, good or evil, will win a given battle. Each of the good races have a certain “worth”. The same is true for the evil races. Given the amount a creatures from each race that show up to battle, we can determine the total “worth” for the good forces and the evil forces. The side with the highest “worth” will win the battle.

Since each race is a name that is paired with a value, its “worth”, we can take this opportunity to practice using JavaScript objects. We can create an object called creatures, and enter two names, good_creatures and evil_creatures. The value will be associated with both of those items will be another object. This object will include the races and their associated “worth”. Once completed, the object will look as so:

Awesome! Let’s keep going. The kata tells us that the function will be given two parameters. Each parameter will be a string of multiple integers separated by a single space. Each string will contain the count of each race on the side of good and evil. The count for each race will be listed in the same order as they are listed in the object we already created.

Okay, so, within our function, let’s first convert these strings into arrays using the .split(‘ ’) method.

At this point, let’s use the creatures object to find the total worth for each good race.

Now that we have the total worth present for each good race. With these values, we can find the total worth present on the side of good.

Now we’re getting there! Let’s repeat that same process for the evil forces.

With the total worth on both the good and evil sides, we can compare the values and see who won. We can use an if statement to account for the scenario of a tie, and use a ternary to evaluate the situation where one of the sides win.

Finally, we can return the battleResults variable, and now identify which side won, or if they tied.

Fantastic! That’s all there is to it. You now have gotten some practice using JavaScript objects, and other interesting features, such as the ternary statement. But most importantly, you know the fate of Middle Earth!

--

--