1

Is there a way in CoffeeScript to reduce the code size but still have the same effect as -

{hours, seconds, minutes} = data
x = {hours, seconds, minutes}
tusharmath
  • 9,120
  • 11
  • 52
  • 70

2 Answers2

3

There are several ways to do it.

The best one is to adopt some helpful library, e.g. underscore or lodash:

x = _.pick data, 'hours', 'seconds', 'minutes'

But if you don't want to include external library to your project, then you may use one of the following methods.

Function call:

x = (->{@hours, @seconds, @minutes}).call data

Define custom reusable pick method:

Object::pick = (args...) ->
  res = {}
  res[k] = @[k] for k in [].concat args
  res

x = data.pick 'hours', 'seconds', 'minutes'
Leonid Beschastny
  • 43,908
  • 9
  • 107
  • 112
0

In ES6, one idiom is

(({hours, seconds, minutes}) => ({hours, seconds, minutes})) (data)
  ^^^^^^^^^^^^^^^^^^^^^^^^^      ^^^^^^^^^^^^^^^^^^^^^^^^^ 
  deconstruct argument           return object constructed 
  into variables                 using object literal
                                 shorthand
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ ^^^^^^
                    DEFINE FAT ARROW FUNCTION                CALL IT 

Whether you think is is good or horrible is ultimately a matter of personal preference.

What we really need is a pick operator in the language, so I could write

{hours, seconds, minutes} PICK data

For this I am proposing #, so

{hours, seconds, minutes} # data

Related: One-liner to take some properties from object in ES 6

Community
  • 1
  • 1