Variable assignment with switch in coffescript

How to use switch for assignment in coffescript? I tried many ways, but could not get it to 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 that 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 method also

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

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

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

Finally 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"

Did I miss something?

+4
source share
1 answer

CoffeeScript has two forms : switch

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
  ...

switch exprsimilar to JavaScript switch: you compare the result exprwith each expression whenand execute whenfrom ==to expr. This form switchis the same as:

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

switch ... when when expr, expr , :

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

, , switch .

, - :

arr = "coffee_script"
switch arr
  when 'coffee_script'
    item.type = arr
  ...
+3

Source: https://habr.com/ru/post/1540575/


All Articles