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?
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
...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With