r/coffeescript • u/mc_hammerd • Feb 05 '16
Can someone examplify comprehensions? the one feature of coffee I haven't used.
so the only thing in coffee i dont use is comprehensions
i build single page web apps and node based linux utils
i havent used them once... whats a good example of using comprehensions?
assuming i already have a 1..10 that prints 1-N, i havent found a use for them
also what are the pitfalls?
7
Upvotes
3
u/mc_hammerd Feb 08 '16 edited Feb 08 '16
turns out i was using them and didnt even know it
like:
foo = 1 if bar == 0i guess you can use them as lambdas, or foreach, and each+apply.
when wrapped in parens they return an array like map.
2
u/[deleted] Mar 27 '16
First off, comprehensions in CoffeeScript aren't a standalone feature. They are a lucky combination of several other features:
whenkeyword;So, let's try to understand it. Firstly, when everything is an expression, a loop also must return something. It's logical that in CoffeeScript it just returns an array of resulting elements. Which makes it similar to, for example, Python's comprehensions. The
whenkeyword allows us to filter the elements over which we iterate. Still, it's a standard loop.Let's assume we have a source array (
src = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16]) and we have to double every second element and return the doubled elements. So we are tempted to write:However, this will not work as expected, and the
destvariable will contain just the last doubled value. Why? Because of the operator precedence, the above statement will just rundest = el * 2for every second element anddestwill contain the last iteration result. That's what parens are for:This will work as expected and return an array into
dest. As it visually looks like actual comprehension constructs in other language, hence the name of this feature.