Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
        ...
like image 890
puchu Avatar asked May 08 '12 15:05

puchu


People also ask

What is CoffeeScript used for?

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.

How do you write a CoffeeScript?

In general, we use parenthesis while declaring the function, calling it, and also to separate the code blocks to avoid ambiguity. In CoffeeScript, there is no need to use parentheses, and while creating functions, we use an arrow mark (->) instead of parentheses as shown below.

How do I know if CoffeeScript is installed?

The coffee and cake commands will first look in the current folder to see if CoffeeScript is installed locally, and use that version if so. This allows different versions of CoffeeScript to be installed globally and locally.


2 Answers

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
like image 108
Linus Thiel Avatar answered Oct 24 '22 09:10

Linus Thiel


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.

like image 38
Ron Martinez Avatar answered Oct 24 '22 11:10

Ron Martinez