eComEvo
eComEvo

Reputation: 12551

CoffeeScript alternative syntax for a while loop

I have this function written in CoffeeScript that I feel should be better written:

addCSS = (files) ->
  i = files.length - 1

  while i >= 0
    $("<link/>",
        rel: "stylesheet"
        href: files[i]
    ).appendTo $("head")
    i--
  return

The files arg is just an array of file paths.

Is there a more succinct/cleaner way to write this in CoffeeScript?

Upvotes: 0

Views: 61

Answers (1)

njzk2
njzk2

Reputation: 39386

A simple

addCSS = (files) ->
  for file in files
    $("<link/>",
        rel: "stylesheet"
        href: file
    ).appendTo $("head")

(no need for return either, although it does prevent coffee from returning a bunch of stuff)

In case you are wondering, because of the horrible behavior of JS with for ... in loop, it is compiled as

for (_i = 0, _len = files.length; _i < _len; _i++) {
    file = files[_i];
    // ...
}

Edit

I realize just now that you are reversing the array, so it would be

for file in files by -1

(supported since 1.5.0)

compiles as for (_i = files.length - 1; _i >= 0; _i += -1) {

Upvotes: 1

Related Questions