Switch..Case Statement Question.

A

Andy

Can someone tell me if the following Switch...Case construct is valid?
I'm wanting to check for multiple values in the Case statement without
explicitly listing each values.
So for example, will case 1-35: work? If this would work, will it
consider all numbers between 1 and 35 inclusive of 1 and 35? Please let
me know if the following will work below:

switch(state){
case 1-35:
case 37:
do something_1;
break;
case 36:
do something_2;
break;
case 38-50:
do something_3;
break;
}


Thank you.
Andy.
 
L

Lee

Andy said:
Can someone tell me if the following Switch...Case construct is valid?
I'm wanting to check for multiple values in the Case statement without
explicitly listing each values.
So for example, will case 1-35: work? If this would work, will it
consider all numbers between 1 and 35 inclusive of 1 and 35? Please let
me know if the following will work below:

switch(state){
case 1-35:
case 37:
do something_1;
break;
case 36:
do something_2;
break;
case 38-50:
do something_3;
break;
}

With less effort and much less wait time, you could have just tested
your sample code yourself. Your first case will match any state that
equals your index value of -34 (1-35).
 
E

Evertjan.

Andy wrote on 28 feb 2005 in comp.lang.javascript:
Can someone tell me if the following Switch...Case construct is valid?
I'm wanting to check for multiple values in the Case statement without
explicitly listing each values.
So for example, will case 1-35: work? If this would work, will it
consider all numbers between 1 and 35 inclusive of 1 and 35? Please let
me know if the following will work below:

did you test it yourself? If not why not?
switch(state){
case 1-35:
case 37:
do something_1;
break;

this part will execute if "state" is -34 or 37,
because 1-35 is 34, I think.

But please test it yourself.
 
A

Andy

I apologize for not having tested myself and wasted your time. Do you
or anyone else knows of a way to check for multiple values without
stating each one like if I'd like to check all values from 1 through 35
how would i do it?

Any help will be appreciated.
 
M

Michael Winter

Andy said:
Can someone tell me if the following Switch...Case construct is valid?
No.

I'm wanting to check for multiple values in the Case statement without
explicitly listing each values.

You cannot. The expression after the case keyword is compared for
strict equality (===) with the expression in the switch statement. In
other words,

switch(2) {
case '2': /* This statement list will not be evaluated. */
}

the statement list for case '2' will not be evaluated because the
expressions do not evaluate to the same type (one is a number, the
other is a string).

You have little choice but to use an if statement.

if(((1 <= state) && (35 >= state)) || (37 == state)) {
/* Between 1 and 35 (inclusive) or is 37 */
something_1();
} else if(36 == state) {
/* Is 36 */
something_2();
} else if((38 <= state) && (50 >= state)) {
/* Between 38 and 50 (inclusive) */
something_3();
}

[snip]

Mike
 
E

Evertjan.

Andy wrote on 28 feb 2005 in comp.lang.javascript:
I apologize for not having tested myself and wasted your time. Do you
or anyone else knows of a way to check for multiple values without
stating each one like if I'd like to check all values from 1 through 35
how would i do it?

Please do not use usenet as a form of email. you are replying to many
here, so quote relevant part of the mail you answer on. Remember
netiquette.

Now "I" have to quote from your old posting:
switch(state){
case 1-35:
case 37:
do something_1;
break;
case 36:
do something_2;
break;
case 38-50:
do something_3;
break;


You could do:

state = 20;
switch(true){
case state>=1&&state<=35:
case state==37:
do something_1;
break;
case state==36:
do something_2;
break;
case state>=38&&state<=50:
do something_3;
break;
case default:
alert('default')
}

This however in my view defies usefulness of switch().
anyway if-else is much more robust:

state = 20;
if ((state>=1&&state<=35)||state==37){
do something_1
else if (state==36)
do something_2
else if (state>=38&&state<=50)
do something_3
else
alert('default');

[not tested]
 
M

Mark Preston

Andy said:
I apologize for not having tested myself and wasted your time. Do you
or anyone else knows of a way to check for multiple values without
stating each one like if I'd like to check all values from 1 through 35
how would i do it?

Any help will be appreciated.
This is where the "greater than or equal to" and "less than or equal to"
operators come in handy. For instance, ">=1 && <=35" is between one and
thirty-five.
 
B

bumbleguppy

You can also try

switch(true){

case(val>1 && val<35): do something;break;
case(val>=35 && val <53):do something;break;
 
E

Evertjan.

bumbleguppy wrote on 05 mrt 2005 in comp.lang.javascript:
You can also try

switch(true){

case(val>1 && val<35): do something;break;
case(val>=35 && val <53):do something;break;

[please quote, usenet is not email]

is the above really more useful than:

if (val>1 && val<35) do_something;
if (val>=35 && val<53) do_something;

?
 
R

rh

Evertjan. said:
bumbleguppy wrote on 05 mrt 2005 in comp.lang.javascript:
You can also try

switch(true){

case(val>1 && val<35): do something;break;
case(val>=35 && val <53):do something;break;

[please quote, usenet is not email]

is the above really more useful than:

if (val>1 && val<35) do_something;
if (val>=35 && val<53) do_something;

?

I'd have to say "No", because the former is syntactically (block)
deficient. ;-)

However, the "switch/case" idiom can be more useful, or at least more
appropriate to use, in some circumstances because of the nature of the
structural encapsulation it provides for a specific filtering task.

The choice shouldn't have any effect on the result of the execution,
but it can have a marked effect on the readability and maintainability
of the code.

../rh
 
B

bumbleguppy

Welcome to 2005 guy.

I don't know what archaic usenet application you are using to view this
thread, but I however am writing this reply in a text box in a webpage.
A Google webpage.

Why would I want to load an html page with the same quoted statemaents
ad naseum when, in my web browser, I can scoll up to see the relevent
subject material?

You remind me of the playground rules in tag. No electricity except in
freeze tag. No tagbacks.

You saw my post. You understood the meaning. Save your sophomoric
nerdish and arbitrary instructions to the next newbie that wants to
"fit in" with the geeks.
 
R

Randy Webb

bumbleguppy said:
Welcome to 2005 guy.

I don't know what archaic usenet application you are using to view this
thread, but I however am writing this reply in a text box in a webpage.
A Google webpage.

A Google webpage that is not a Usenet application but an attempt at a
web-based application for interfacing to Usenet.
Why would I want to load an html page with the same quoted statemaents
ad naseum when, in my web browser, I can scoll up to see the relevent
subject material?

Are you actually stupid enough to believe that rubbish that you spout?
 
R

Richard Cornford

bumbleguppy said:
Welcome to 2005 guy.

I don't know what archaic usenet application you are
using to view this thread, but I however am

Whatever _you_ may be doing is irrelevant. Usenet is a one-to-many
communication medium where the needs/wishes/interest of the many
outweigh all personal preferences. Saving yourself a little effort in
exchange for wasting the time of hundreds or thousands of others is
objectionable and likely to be considered rude.
writing this reply in a text box in a
webpage. A Google webpage.

Recent changes in google's Usenet interface have rendered it on a par
with the very worst providers of web-based access to Usenet
(Forum4designers.com) and the only reasonable advice now possible is to
abandon using google groups in favour of some superior web-based
provider or (preferably) access Usenet directly through an NTTP server
(as provided by any ISP worthy of the name) using real newsreader
software.
Why would I want to load an html page

comp.lang.javascirpt is a plain text _only_ newsgroup.
with the same quoted statemaents
ad naseum when,

The convention is to _only_ quote the material that is being respond to,
and trim the rest. It is done to provide a context for the response.
in my web browser, I can scoll up to see
the relevent subject material?

What ever you can do says nothing bout what the many who read your posts
can do (or what they would prefer to do). You (alone) will never be the
arbiter of what it correct.
You remind me of the playground rules in tag. No
electricity except in freeze tag. No tagbacks.

Games, and many other things, work best when everyone plays by the same
rules. The 'rules', the conventions for Usenet posting, have been around
for a long time (more than 20 years), evolved to suite the medium, and
can be found by reading the groups FAQ (the reading of which is a
pre-requisite for participation in any technical Usenet group that
provides a FAQ).
You saw my post. You understood the meaning. Save
your sophomoric nerdish and arbitrary instructions to
the next newbie that wants to "fit in" with the geeks.

Are you inviting that active hostility of regulars on this group?

Richard.
 
R

Richard Cornford

rh said:
I'd have to say "No", because the former is syntactically
(block) deficient. ;-)
<snip>

To be honest I find the former superior, but only because of one
omission in the latter; there should be an - else - in front of the
second - if - statement. The conditions are mutually exclusive and there
is no reason to evaluate the second after the first has evaluated to -
true.

Range testing in - if/else if/else - blocks seems more readable than
controlling a - switch - from a numeric or boolean literal and then
evaluating expressions in the - case - clauses (useful as that facility
may be in other contexts).

Richard.
 
J

John W. Kennedy

Evertjan. said:
bumbleguppy wrote on 05 mrt 2005 in comp.lang.javascript:

You can also try

switch(true){

case(val>1 && val<35): do something;break;
case(val>=35 && val <53):do something;break;


[please quote, usenet is not email]

is the above really more useful than:

if (val>1 && val<35) do_something;
if (val>=35 && val<53) do_something;

Actually, yes. You're missing an 'else'.

---
John W. Kennedy
"Those in the seat of power oft forget their failings and seek only the
obeisance of others! Thus is bad government born! Hold in your heart
that you and the people are one, human beings all, and good government
shall arise of its own accord! Such is the path of virtue!"
-- Kazuo Koike. "Lone Wolf and Cub: Thirteen Strings" (tr. Dana Lewis)
 
E

Evertjan.

John W. Kennedy wrote on 06 mrt 2005 in comp.lang.javascript:
Evertjan. said:
bumbleguppy wrote on 05 mrt 2005 in comp.lang.javascript:

You can also try

switch(true){

case(val>1 && val<35): do something;break;
case(val>=35 && val <53):do something;break;


[please quote, usenet is not email]

is the above really more useful than:

if (val>1 && val<35) do_something;
if (val>=35 && val<53) do_something;

Actually, yes. You're missing an 'else'.

That being my [inconsequental in this example] mistake
does not per se make it less useful then the switch(true)
 
L

Lee

bumbleguppy said:
Welcome to 2005 guy.
You saw my post. You understood the meaning. Save your sophomoric
nerdish and arbitrary instructions to the next newbie that wants to
"fit in" with the geeks.

Don't be so quick to rule out the possibility that you lack the
experience to understand why the request is reasonable. That's
a really good way to make yourself appear to be spectacularly
ignorant.

Insulting people for making a request whose value you fail to
understand makes you look that much worse.
 
R

rh

Richard Cornford wrote:

Range testing in - if/else if/else - blocks seems more readable than
controlling a - switch - from a numeric or boolean literal and then
evaluating expressions in the - case - clauses (useful as that facility
may be in other contexts).

So it would seem, although I think that's in large part due to lack of
some Javascript switch/case facility that's seen in other languages.

In the greater scheme of things, I tend to view the distinction between
switch/case and if/else as the former being more for conditioning
(i.e., setup) and the latter more for program flow control. Of course,
if/else is always favoured and appropriate when the set of cases to be
distinguished is small.

Not a perfect substitute, but perhaps helpful in the context of numeric
range filtering, would be something like:

<script type="text/javascript">

Number.prototype.inRng = function( str ) {
var testSet = str.split( "," );
for ( var k = 0; k < testSet.length; k++ ) {
var rng = testSet[ k ]
.replace( /(\d|y)\s*-\s*([+-]?(\d|I))/g, "$1#$2" )
.split( "#" );
if ( typeof rng[ 1 ] == "undefined" ) rng[ 1 ] = rng[ 0 ];
if ( this >= rng[ 0 ] && this <= rng[ 1 ] ) return true;
}
return false;
}

var z = 33;

switch ( true ) {

case z.inRng( '1-35, 37' ) :
//..
break;

case z == 36 :
//..
break;

case z.inRng( '38-50' ) :
//..
break;

default :
//..
}
</script>

../rh
 
E

Evertjan.

rh wrote on 06 mrt 2005 in comp.lang.javascript:
Number.prototype.inRng = function( str ) {

Try this:

<script type="text/javascript">
var myCase = 'myCase';
var mydo = 'mydo';
var myDefault = 'myDefault';
var res,a;

function mySwitch(){
var base = mySwitch.arguments[0]
for (var i=1;i<mySwitch.arguments.length;i++){
a = mySwitch.arguments
if(i==0)var val=a
else if (a==myCase)res=false
else if ((a==mydo&&res)||a==myDefault){
eval(mySwitch.arguments[++i])
return }
else if (!res){
if (/\d+\-\d+/.test(a))
res = (base>=1*a.replace(/-\d+/,''))&&
(base<=1*a.replace(/\d+-/,''))
else
res = (base==a)
}
}
}


mySwitch(

6,

myCase,2,3,4,
mydo,"alert('TwoThreeFour')",
myCase,"5-7",8,
mydo,"alert('FiveToEight')",
myCase,9,100,
mydo,"alert('NineOrHundred')",
myDefault,
"alert('NoneOfThem')"
)

</script>
 
R

rh

Evertjan. said:
rh wrote on 06 mrt 2005 in comp.lang.javascript:

Try this:

mySwitch(

6,

myCase,2,3,4,
mydo,"alert('TwoThreeFour')",
myCase,"5-7",8,
mydo,"alert('FiveToEight')",
myCase,9,100,
mydo,"alert('NineOrHundred')",
myDefault,
"alert('NoneOfThem')"
)

Well, you'll have to be given points for a adopting an inventive and
novel approach, but I don't think I want to go there.

Note that as soon as you call the "mySwitch" function, you've lost the
current execution context. That means that if you want to do something
that's actually useful in a "mydo", such as test or assign to a local
variable from the original context, you're snookered.

../rh
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,764
Messages
2,569,564
Members
45,041
Latest member
RomeoFarnh

Latest Threads

Top