Jerry Zhang
Jerry Zhang

Reputation: 1301

CoffeeScript - How to break a long destructuring assignment into multiple lines

Given a javascript object in coffeescript form like this:

opts = 
  longProperty: 'value1'
  veryLongProperty: 'value2'
  veryVeryLongProperty: 'value3'
  veryVeryVeryLongProperty: 'value4'

A normal destructuring statement in coffeescript will be like this:

{ longProperty, veryLongProperty, veryVeryLongProperty, veryVeryVeryLongProperty } = opts

Question: is it possible to separate the assignment into multiple lines in an elegant way? What's the most elegant way to do it?

Upvotes: 1

Views: 708

Answers (2)

Jeremy
Jeremy

Reputation: 1924

The most elegant way would be to use shorter property names, and then deconstructing them in a single line.

opts = 
  shorter: 'value1'
  nicer: 'value2'
  faster: 'value3'
  better: 'value4'

{ shorter, nicer, faster, better } = opts

If that's impossible, you could try categorizing your properties into sub-objects:

opts = 
  subcat1:
    longProperty: 'value1'
    veryLongProperty: 'value2'
  subcat2:
    veryVeryLongProperty: 'value3'
    veryVeryVeryLongProperty: 'value4'

{ subcat1, subcat2 } = opts
console.log subcat1.longProperty

# or if you just need access to one property...

{ subcat1: {longProperty}, subcat2 } = opts
console.log longProperty

By putting your properties into categories, you might even be able to shorten their names.

Upvotes: 0

apxp
apxp

Reputation: 5894

Answer is yes.

How about:

{ 
longProperty, 
veryLongProperty, 
veryVeryLongProperty, 
veryVeryVeryLongProperty 
} = opts

Example

Upvotes: 2

Related Questions