3

Is there any coffeescript specific trickery that would make this look neater:

index = (->
          if segment == 'index'
            return 0
          else if segment == 'inbox'
            return 2

          1
        )()

3 Answers 3

7

Yes, a switch expression:

index = switch segment
  when 'index' then 0
  when 'inbox' then 2
  else 1
Sign up to request clarification or add additional context in comments.

Comments

1

You could use an inline if ... then ... else statement broken up into multiple lines (for readability) by using the \ character.

index = if segment == 'index' then 0 \
        else if segment == 'inbox' then 2 \
        else 1

This is useful if your conditional logic is too complex for a simple switch block.

Comments

0

Yes, the CoffeeScript-specific existential operator:

index = {'index': 0, 'inbox': 2}[segment] ? 1

You could also use an inline if statement to get rid of the function call:

index = if segment == 'index' then 0 else if segment == 'inbox' then 2 else 1

But an inline if wouldn't be any harder in straight Javascript:

index = segment == 'index' ? 0 : segment == 'inbox' ? 2 : 1

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.