Denny Mueller
Denny Mueller

Reputation: 3615

|| statement in a coffeescript switch statement

How can I use an || (or) statement in a coffeescript switch? Need that because its the same assignment for different types.

switch type
  when 'pdf'
    icon = 'file-pdf-o'
  when 'mpg' || 'mpg4' || 'flv' || 'mp4'
    icon = 'film'
  else
    icon = 'file'

This doenst work. It just checks for the first string 'mpg' How can I achieve that correctly?

Upvotes: 1

Views: 492

Answers (1)

Oka
Oka

Reputation: 26365

You can use comma separated lists to cause the switch statement to 'fall-through' its options. This is the same as using an empty case with no break in vanilla JavaScript.

switch type
  when 'pdf'
    icon = 'file-pdf-o'
   when 'mpg', 'mpg4', 'flv', 'mp4'
     icon = 'film'
   else
     icon = 'file'

compiles to:

switch (type) {
  case 'pdf':
    icon = 'file-pdf-o';
    break;
  case 'mpg':
  case 'mpg4':
  case 'flv':
  case 'mp4':
    icon = 'film';
    break;
  default:
    icon = 'file';
}

Upvotes: 3

Related Questions