Switch statment with empty control expression defaults to false
# CS
switch
when "A" then console.log "Hi"
else console.log "Bye"
// Generated JS
switch (false) {
case !"A":
console.log("Hi");
break;
default:
console.log("Bye");
}
CS should report this as an invalid syntax.
Also, I find it strange that ! is prepend for all values in case statament in generated JS.
This is on purpose and useful. You are switching on true - a nice replacement for a series of if-else statements. It compiles to switching on false as it is slightly shorter to cast each of the cases to a boolean with a single ! rather than !!.
@gkz Hmm, I see.
[enable, alerted] = [off, on]
switch
when enable then alert "Enabled"
when alerted then alert "Altered"
else alert "Normal"
However, don't see ths documented on the official site.
It's intentional and undocumented. There's already an issue open that mentions that this needs to be documented. See #1808. @gabehollombe volunteered to improve the documentation.
I was thinking of a good case of empty switch as part of documenting this feature and I think that it's does better in conditional assignment of value, which improves redability due to use of indent, unlike in if else.
# using switch
score = 90
grade = switch
when score >= 97 then "A+"
when score >= 94 then "A"
when score >= 90 then "A-"
when score >= 87 then "B+"
when score >= 84 then "B"
when score >= 80 then "B-"
when score >= 78 then "C"
when score >= 75 then "D"
else "F"
alert grade
# using if else
score = 90
grade = if score >= 97 then "A+"
else if score >= 94 then "A"
else if score >= 90 then "A-"
else if score >= 87 then "B+"
else if score >= 84 then "B"
else if score >= 80 then "B-"
else if score >= 78 then "C"
else if score >= 75 then "D"
else "F"
alert grade
Yep, that's a great example. Do you want me to just go with that, and polish it a bit with some context and wordsmithing?
On Wed, Jul 4, 2012 at 10:56 AM, OnesimusUnbound < [email protected]
wrote:
I was thinking of a good case of empty switch as part of documenting this feature and I think that it's does better in conditional assignment of value, which improves redability due to use of indent, unlike in
if else.# using switch score = 90 grade = switch when score >= 97 then "A+" when score >= 94 then "A" when score >= 90 then "A-" when score >= 87 then "B+" when score >= 84 then "B" when score >= 80 then "B-" when score >= 78 then "C" when score >= 75 then "D" else "F" alert grade # using if else score = 90 grade = if score >= 97 then "A+" else if score >= 94 then "A" else if score >= 90 then "A-" else if score >= 87 then "B+" else if score >= 84 then "B" else if score >= 80 then "B-" else if score >= 78 then "C" else if score >= 75 then "D" else "F" alert grade
Reply to this email directly or view it on GitHub: https://github.com/jashkenas/coffee-script/issues/2416#issuecomment-6752131
@gabehollombe sure, go ahead ;-)
Pull request is in: https://github.com/jashkenas/coffee-script/pull/2417