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.
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.
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.
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/
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With