puchu
puchu

Reputation: 3662

coffee script switch without break

Is it possible to use switch in coffeescript without break?

switch code                      switch (code) {
    when 37 then                     case 37: break;
    when 38 then           ->        case 38: break;
    when 39 then                     case 39: break;
    when 40                          case 40:
        ...                              ...

I thought this will work but failed:

switch code
    when 37 then continue
    when 38 then continue  ->    not valid
    when 39 then continue
    when 40
        ...

Upvotes: 19

Views: 24034

Answers (4)

Koen.
Koen.

Reputation: 26999

Old question already, but if you place the commas on the next line, it works as expected, without the backslash line continuation showed by @Ron Martinez

switch code
  when 37
     , 38
     , 39
     , 40
    console.log "Some Number"
  else
    console.log "Default"

Which will compile to:

switch (code) {
  case 37:
  case 38:
  case 39:
  case 40:
    return console.log("Some Number");
  default:
    return console.log("Default");
}

Upvotes: 2

benathon
benathon

Reputation: 7653

It's totally possible, just use a classic javascript and pass it through with backtics

`
switch (code) {
    case 37:
    case 38:
    case 39:
    case 40:
        // do the work of all four
    default:
        //default
}
`

Upvotes: 4

Ron Martinez
Ron Martinez

Reputation: 195

You can use line continuation to help with this. For example:

name = 'Jill'

switch name
  when 'Jill', \
       'Joan', \
       'Jess', \
       'Jean'
    $('#display').text 'Hi!'
  else
    $('#display').text 'Bye!'

Check it out in action here.

Upvotes: 12

Linus Thiel
Linus Thiel

Reputation: 39261

Not really. From the docs:

Switch statements in JavaScript are a bit awkward. You need to remember to break at the end of every case statement to avoid accidentally falling through to the default case. CoffeeScript prevents accidental fall-through, and can convert the switch into a returnable, assignable expression. The format is: switch condition, when clauses, else the default case.

What you can do, though, is specify several values in a case, if they are to be treated equally:

switch day
  when "Mon" then go work
  when "Tue" then go relax
  when "Thu" then go iceFishing
  when "Fri", "Sat"
    if day is bingoDay
      go bingo
      go dancing
  when "Sun" then go church
  else go work

Upvotes: 48

Related Questions