Tuesday, February 4, 2014

My path to JavaScript: Functions, closures and recursion

Today I read chapters 5 (Functions) and 6 (Applied Functions and Closures) of Test Driven JavaScript development. In them, Christian Johansen goes deep into JavaScript powerful functions talking about functions as first class objects, closures, free variables, recursion, binding, namespaces, etc. I'm enjoying a lot his book.

To practice a bit with recursion and closures and also get more acquainted with Jasmine, I decided to do the FizzBuzz kata again but applying some of these concepts. I did TDD to get to a result which was very similar to the solution of FizzBuzz that I produced yesterday to try Karma and Jasmine.

This is the version from yesterday:
After the new version of FizzBuzz was working, I started to refactor its code focusing on removing as much duplication as possible and trying to make the code more general, so that, it could accept different sets of substitution functions each of them still based on "multiple of" predicates. I also tried to play with the scope rules to make private helper functions and use free variables to reduce the necessary number of parameters.

This is the new version of the code:

It has two public functions: makeSubstitution that is factory of substitution functions and substitute that is the generalization of the original fizzbuzz function. Like fizzbuzz did, substitute also receives a list of numbers that will be substituted only if they fulfill certain condition (being a multiple of 3, being a multiple of 5, etc). The difference is that substitute also receives a list of substitution functions.

Taking this into account, you can see that fizzbuzz(numbers) is equivalent to substitute(numbers, [makeSubstitution(3, "Fizz"), makeSubstitution(5, "Buzz")]).

This way we can create new games using different lists of substitution functions (that use "multiple of" predicates) without having to change substitute's code.

Have a look at "FizzKozz" at the end of the tests:

JavaScript is a lot of fun!

No comments:

Post a Comment