andrew
andrew

Reputation: 412

Is there a nice way to get hash as a loop result in coffeescript?

In coffeescript loops are expressions and returns an array. For example, we can do

func = (name) -> name.toUpperCase()
result = (func prop for prop in ['a', 'b'])

and get as a result:

['A','B']

But what if I want to get hash table (object) instead of array? How to modify the above example to get { a: 'A', b: 'B' } ?

I know, that I can do id like this:

func = (name) -> name.toUpperCase()
result = {}
result[prop] = func prop for prop in ['a', 'b']
result

Too verbose! May be there is a nicer way?

Upvotes: 0

Views: 42

Answers (1)

Linus Thiel
Linus Thiel

Reputation: 39251

While not as nice as a real object comprehension, you can use Array::reduce for this. For your example in particular, using a "transformer" function such as:

transform = (f) -> (prev, curr) ->
  prev[curr] = f curr
  prev

And your func:

func = (name) -> name.toUpperCase()

You can reduce your array with transform and func like so:

result = ['a', 'b'].reduce transform(func), {}

See Approximating object comprehension one-liners in CoffeeScript using Array.reduce() for a lengthier explanation and more examples.

Upvotes: 2

Related Questions