Thursday, July 17, 2014

Kata: Rotate an array in place in JavaScript

Álvaro García and I were pairing yesterday after work.

We practised coding the Rotate an array in place kata in Python.

It was great fun and we discussed about naming, scaffolding tests, closures, free variables and deleting tests.

Once back at home, I redid the kata in JavaScript. You can see the resulting code in GitHub. I commited every time I got to green and after every refactoring so you can follow the process.

In this post I just want to highlight what Álvaro and I did to optimize the code a bit.

These are the tests we kept after having a first working version of the code:


and this is the corresponding code:


This code worked also for steps greater or equal that the array size, only that in that particular case it would do more work than necessary. To avoid that extra work you just need to realize that a rotation by k steps yields the same result as a rotation by n * k steps, where n is a positive integer.

Since we were practising our TDD skills, we wanted to write first a failing test that forced us to write that optimization. Not that TDD should be used for that. It was only a way to set ourselves a tiny challenge for us to practise.

We realized that we could use an assertion on the number of calls to the swap helper to force the desired change, but first we had to make the function swap accessible from the outside:


in order to spy on it:


The last test was now failing, as we intended, for making to many calls to swap.

It took just a small change to the code to make the test pass:


This way we could assert that a rotation by k steps yielded the same result as a rotation by n * k steps, where n is a positive integer.

Once we had that optimization in place, we made swap private again:


for which we had to stop spying on it from the tests:


Next we examined the tests to see which ones were overlapped and could be removed. They had been useful as scaffolding to build the functionality, but once there they weren't adding much value. In our opinion keeping these scaffolding tests or not, is something that needs to be ponder in a case by case basis.

After removing those tests, I renamed the remaining tests and played a bit with augmenting the Array object prototype to finally get to the following tests:


I think that although this kata is very simple, you can make a lot from it and have fun.

Thanks Álvaro for the great pairing experience, I hope we'll go on having fun with other katas.

No comments:

Post a Comment