Coffeescript dictionary is installed by default

In Python, if you have a dictionary that consists of lists like

mydict = {'foo': [], 'bar':[3, 4]} 

and if you want to add something to these lists, you can do

  mydict.setdefault('baz', []).append(5) 

don't write

 key, list_element = 'baz', 5 if key in mydict: mydict[key].append(list_element) else: mydict[key] = [list_element] 

is there an equivalent for this in coffeescript?

+4
source share
3 answers

Here is one of the options:

 (mydict.baz or (mydict.baz = [])).push(5) 

In this case, CoffeeScript is very similar to the JavaScript it generates:

 (mydict.baz || (mydict.baz = [])).push(5); 
+1
source

I recommend not using || / or for membership verification is basically a smart trick that will silently play false values. i prefer to write

 ( mydict[ name ]?= [] ).push value 

which I find clearer; he assumes that if mydict does not have an entry for name or if it is null or undefined , then an empty list should be put at this point.

+8
source

If you do not mind using underscore.js .

http://underscorejs.org/#defaults

 var iceCream = {flavor : "chocolate"}; _.defaults(iceCream, {flavor : "vanilla", sprinkles : "lots"}); => {flavor : "chocolate", sprinkles : "lots"} 
0
source

Source: https://habr.com/ru/post/1498490/


All Articles