CoffeeScript multi value switch statement?
switch @user &a开发者_JAVA百科mp;& @other
when 'user' && true
...
when 'user2' && false
...
Is something like this possible? It's not working for some reason. Thanks!
It's a pity that JS doesn't think [1, 2] === [1, 2]
(since they're different references); otherwise you could use arrays to do what you want.
Instead, here's a function:
multiSwitch = (values, cases...) ->
for c in cases
match = true
for i in [0...values.length]
unless c[i] is values[i]
match = false
break
return c[values.length]() if match
return
Use it like this:
multiSwitch [@user, @other],
['user', true, ->
console.log 'case 1'
]
['user2', false, ->
console.log 'case 2'
]
Depending on what you're doing, it may be easier to, say, concatenate your multiple values into a string and do a switch
on that.
精彩评论