fancy
fancy

Reputation: 51453

CoffeeScript multi value switch statement?

switch @user && @other
    when 'user' && true
        ...
    when 'user2' && false
       ...

Is something like this possible? It's not working for some reason. Thanks!

Upvotes: 0

Views: 1152

Answers (1)

Trevor Burnham
Trevor Burnham

Reputation: 77426

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.

Upvotes: 1

Related Questions