CoffeeScript Object Comprehensions (Excerpt from CoffeeScript in Action)

   By Patrick Lee CoffeeScript Object Comprehensions This article is based on CoffeeScript in Action, to be published Summer 2012. It is being reproduced here by permission from Manning Publications. Manning early access books and ebooks are sold exclusively through Manning. Visit the book’s page for more information. To add up all the view counts for every property on the views object, you need to use a comprehension. In this article, based on chapter 4 of CoffeeScript in Action, you will learn how to use comprehensions to transform the properties and values of an object into other values.
Imagine you have a website with two pages. You want to track how many views each page on your website gets and the total number of views for all pages. Your website pages live on specific URLs but are referred to simply as the pages ren and stimpy for the sake of clarity. If the ren page has so far received 30 views and the stimpy page 10 views then that can be represented as: views = 'ren': 30 'stimpy': 10   Storing a property on the object is by assignment, so a count can be incremented using: views.ren = views.ren + 1   How about adding up all the view counts for every property on the views object though? How is that done? By using a comprehension. In this article, you will learn how to use comprehensions to transform the properties and values of an object into other values. Object comprehensions Comprehensions allow you to deal the elements of an array without having to write a bunch of boilerplate and iterate manually through every single thing in the array one by one, again and again and again. Check it out: number + 1 for number in [1,2,3,4,5] # [2,3,4,5,6]   Object comprehensions in CoffeeScript work similarly to how array comprehensions work. They also have a similar basic format to array comprehensions except they use the word of instead of in: expression for property of object   What does it do? Listing 1 is a side-by-side comparison with the JavaScript’s for…in loop that CoffeeScript replaces with object comprehensions:   Listing 1 Comprehension compared to for…in loop
CoffeeScript JavaScript
movie = title: 'From Dusk till Dawn' released: '1996' director: 'Robert Rodriguez' writer 'Quentin Tarantino' for property of movie console.log property var movie = { title: 'From Dusk till Dawn', released: '1996', director: 'Robert Rodriguez', writer: 'Quentin Tarantino' } for (var property in movie) { } console.log(property);
In the basic case, the JavaScript version is fine. However, the JavaScript version uses statements. In CoffeeScript, you should prefer expressions. To see the power of expressions in this specific case compare getting an array of property names from the object in listing 2.

Page 1 of 3 | Next page