Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

variable assignment with switch in coffescript

How to use switch for assignment in coffescript? Tried many ways but couldn't make it work.

item = { name: "ahola" }
arr = "coffee_script"

switch arr
 when arr.match /script/
   item.type = arr

 alert item.name + " : " + item.type
 # alerts  "ahola : undefined"

even this doesn't work

item = { name: "ahola" }
arr = "coffee_script"

switch arr
 when arr == "coffee_script"
   item.type = arr

alert item.name + " : " + item.type
# alerts  "ahola : undefined"

tried this way also

item = { name: "ahola" }
arr = "coffee_script"

item.type = switch arr
 when arr.match /script/
   arr

alert item.name + " : " + item.type
# alerts  "ahola : undefined"

At last found this also doesn't work

item = { name: "ahola" }
arr = "coffee_script"

item.type = switch arr
 when true
   arr

alert item.name + " : " + item.type
# alerts  "ahola : undefined"

Am I missing something?

like image 386
roxxypoxxy Avatar asked Oct 01 '22 19:10

roxxypoxxy


1 Answers

There are two forms of switch in CoffeeScript:

switch expr
  when expr1
    result1
  ...
  else
    default_result

and

switch
  when expr1
    result1
  ...
  else
    default_result

Both forms are, of course, expressions so you can say:

x = switch expr
  when val then result
  ...

and

x = switch
  when expr then result
  ...

The switch expr is like a JavaScript switch: you compare the result of expr with each when expression and execute the when that is == to expr. This form of switch is the same as:

if(expr == expr1)
  result1
else if(expr == expr2)
  result2
...
else
  default_result

The switch ... when form executes the first when expr where expr is true so it is a fancy way of saying:

if(expr1)
  result1
else if(expr2)
  result2
...
else
  default_result

All of your attempts appear to be trying to mix the two forms of switch and confusion ensues.

I think you're looking for something like this:

arr = "coffee_script"
switch arr
  when 'coffee_script'
    item.type = arr
  ...
like image 97
mu is too short Avatar answered Oct 03 '22 10:10

mu is too short