CoffeeScript empty switch
Sometimes a switch is useful, but one or more of the switch conditions are not straight forward to setup.
Here's the default documented switch behaviour:
go = (activity) ->
alert(activity)
bingoDay = "Sat"
day = 'Tue'
switch day
when "Mon" then go 'work'
when "Tue" then go 'relax'
when "Thu" then go 'iceFishing'
when "Fri", "Sat"
if day is bingoDay
go 'bingo'
go 'dancing'
when "Sun" then go 'church'
else go 'work'
Here's a contrived empty switch version.
Notice that we can use any truth condition to switch.
day = "Sat"
switch
when 5 is 7
go 'this can never run'
when day is "Mon" then go 'work'
when day is "Tue" then go 'relax'
when day is "Thu" then go 'iceFishing'
when day is "Sun" then go 'church'
when bingoDay is day
go 'bingo'
when day is "Wed"
go 'work'
else go 'dancing'
Because sometimes a switch is just more elegant than a if - else if - else
Written by Francois Paul
Related protips
Have a fresh tip? Share with Coderwall community!
Post
Post a tip
Best
#Switch
Authors
Sponsored by #native_company# — Learn More
#native_title#
#native_desc#