piggyback
piggyback

Reputation: 9254

Loop in coffee script?

I'm translating a piece of code from javascript to coffeescript.

  for (var i = 0, len = keys.length; i < len; i++) {
    k = keys[i];
    if (!mailOptions.hasOwnProperty(k))
      mailOptions[k] = app.set('mailOptions')[k]
  }

I have no idea how to approach to it and on the doc website is not clear, can someone give me a clear explanation? thank you very much!

Upvotes: 0

Views: 570

Answers (2)

thejh
thejh

Reputation: 45568

for key in keys
  if not mailOptions.hasOwnProperty key
    mailOptions[key] = (app.set 'mailOptions')[key]

Or guard-style:

for key in keys when not mailOptions.hasOwnProperty key
  mailOptions[key] = (app.set 'mailOptions')[key]

Compiles to:

var key, _i, _len;

for (_i = 0, _len = keys.length; _i < _len; _i++) {
  key = keys[_i];
  if (!mailOptions.hasOwnProperty(key)) {
    mailOptions[key] = (app.set('mailOptions'))[key];
  }
}

Upvotes: 4

glortho
glortho

Reputation: 13200

Here's one way (from here: http://js2coffee.org/):

i = 0
len = keys.length

while i < len
  k = keys[i]
  mailOptions[k] = app.set("mailOptions")[k]  unless mailOptions.hasOwnProperty(k)
  i++

But I wouldn't do it this way. I would just do:

for k in keys
  mailOptions[k] = app.set("mailOptions")[k] unless mailOptions.hasOwnProperty k

This outputs the following (excluding var, which it also outputs):

for (_i = 0, _len = keys.length; _i < _len; _i++) {
  k = keys[_i];
  if (!mailOptions.hasOwnProperty(k)) {
    mailOptions[k] = app.set("mailOptions")[k];
  }
}

Or, if you wanted to be fancier, which I don't advise in this situation, since it sacrifices some readability:

(mailOptions[k] = app.set("mailOptions")[k] unless mailOptions.hasOwnProperty k) for k in keys

Upvotes: 1

Related Questions