Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

coffeescript dictionary set 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 into that lists you can do

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

not to 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?

like image 331
oguzalb Avatar asked Jan 13 '23 14:01

oguzalb


1 Answers

i recommend against using ||/ or to test for membership—it's basically a clever trick that will silently fail against falsy values. i prefer to write

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

which i find clearer; it assumes that in case mydict does not have an entry for name or that value is null or undefined, then an empty list should be put there at this point.

like image 64
flow Avatar answered Jan 22 '23 16:01

flow