Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Coffeescript ||= analogue?

I'm primarily a Rails developer, and so in whipping up a little script for my company's Hubot instance, I was hoping to accomplish the following:

robot.brain.data.contacts ||= {} 

Or, only make this new hash if it doesn't already exist. The idea being that I want to have a contacts array added dynamically through the script so I don't have to modify Hubot's source, and I obviously don't want to overwrite any contacts I add to it.

Question: is there a quick little construct like the Rails ||= that I can use in Coffeescript to achieve the above goal?

Cheers.

like image 516
Nick Coelius Avatar asked Mar 05 '12 19:03

Nick Coelius


People also ask

Should you use CoffeeScript?

CoffeeScript is something that makes even good JavaScript code better. CoffeeScript compiled code can do everything that natively written JavaScript code can, only the code produced by using CoffeeScript is way shorter, and much easier to read.

What is CoffeeScript used for?

CoffeeScript is a programming language that compiles to JavaScript. It adds syntactic sugar inspired by Ruby, Python, and Haskell in an effort to enhance JavaScript's brevity and readability. Specific additional features include list comprehension and destructuring assignment.


2 Answers

You can use ?= for conditional assignment:

speed ?= 75 

The ? is the "Existential Operator" in CoffeeScript, so it will test for existence (not truthiness):

if (typeof speed === "undefined" || speed === null) speed = 75; 

The resulting JS is a bit different in your case, though, because you are testing an object property, not just a variable, so robot.brain.data.contacts ?= {} results in the following:

var _base, _ref; if ((_ref = (_base = robot.brain.data).contacts) != null) {   _ref; } else {   _base.contacts = {}; }; 

More info: http://jashkenas.github.com/coffee-script/

like image 129
coreyward Avatar answered Sep 23 '22 06:09

coreyward


I personally use or= instead of ?= mainly because that's what I call ||= (or-equal) when I use it in Ruby.

robot.brain.data.contacts or= {} 

The difference being that or= short-circuits when robot.brain.data.contacts is not null, whereas ?= tests for null and only sets robot.brain.data.contacts to {} if not null.

See the compiled difference.

As mentioned in another post, neither method checks for the existence of robot, robot.brain or robot.brain.data, but neither does the Ruby equivalent.

Edit:

Also, in CoffeeScript or= and ||= compile to the same JS.

like image 28
Sandro Avatar answered Sep 23 '22 06:09

Sandro