Smooth CoffeeScript

Page 72

Data Structures paragraphs = email.split '\n' for paragraph in paragraphs handleParagraph paragraph livingCats howMany = 0 for cat of findLivingCats() howMany++ show 'There are ' + howMany + ' cats.'

The whole algorithm is now encapsulated by a function. This means that it does not leave a mess after it runs: livingCats is now a local variable in the function, instead of a top-level one, so it only exists while the function runs. The code that needs this set can call findLivingCats and use the value it returns. It seemed to me that making handleParagraph a separate function also cleared things up. But this one is so closely tied to the cat-algorithm that it is meaningless in any other situation. On top of that, it needs access to the livingCats variable. Thus, it is a perfect candidate to be a functioninside-a-function. When it lives inside findLivingCats, it is clear that it is only relevant there, and it has access to the variables of its parent function. This solution is actually bigger than the previous one. Still, it is tidier and I hope you will agree that it is easier to read.

◦•◦ The program still ignores a lot of the information that is contained in the e-mails. There are birth-dates, dates of death, and the names of mothers in there. To start with the dates: What would be a good way to store a date? We could make an object with three properties, year, month, and day, and store numbers in them. whenWasIt = year: 1980, month: 2, day: 1

But CoffeeScript already provides a kind of object for this purpose. Such an object can be created by using the keyword new: whenWasIt = new Date 1980, 1, 1 show whenWasIt

71


Issuu converts static files into: digital portfolios, online yearbooks, online catalogs, digital photo albums and more. Sign up and create your flipbook.