SitePoint Sponsor

User Tag List

Results 1 to 5 of 5
  1. #1
    SitePoint Member
    Join Date
    Aug 2010
    Posts
    2
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Optimize an IF statement

    I would like to make the following statement clearner. I'm thinking something like the SQL "variable IN (value1, value2, value2, etc.)" operator.

    Any ideas?

    Code JavaScript:
    if((e.which > 47 && e.which < 58) || (e.which > 95 && e.which < 106) || e.which==8 || e.which == 46 || e.which == 37 || e.which == 39 || e.which == 13) return e.which;

  2. #2
    SitePoint Member
    Join Date
    Aug 2010
    Posts
    2
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    I did find one alternative - not necessarily better, but different:

    Code JavaScript:
    if([8,13,37,39,46,48,49,50,51,52,53,54,55,56,57,96,97,98,99,100,101,102,103,104,105].indexOf(e.which) > -1) return e.which;

  3. #3
    SitePoint Member
    Join Date
    Sep 2005
    Posts
    16
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    I'm sure there's a clean mathematical way to do it, but

    /^(8|3[79]|13|4[68-9]|5[0-7]|9[6-9]|10[0-5])$/.test(e.which)

  4. #4
    SitePoint Member
    Join Date
    Apr 2010
    Posts
    3
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Not sure how "optimal" it would be (a little, I think), but converting this to a switch may be a bit more readable.
    Questions are the path to wisdom,
    But answers are the proof of it!

  5. #5
    SitePoint Addict sdleihssirhc's Avatar
    Join Date
    Feb 2009
    Posts
    387
    Mentioned
    1 Post(s)
    Tagged
    0 Thread(s)
    Another way is with an object:

    Code javascript:
    var good = {
    	8: 1,
    	13: 1,
    	37: 1,
    	39: 1,
    	46: 1,
    	48: 1,
    	49: 1,
    	50: 1,
    	51: 1,
    	52: 1,
    	53: 1,
    	54: 1,
    	55: 1,
    	56: 1,
    	57: 1,
    	96: 1,
    	97: 1,
    	98: 1,
    	99: 1,
    	100: 1,
    	101: 1,
    	102: 1,
    	103: 1,
    	104: 1,
    	105: 1
    };
    return good[e.which];

    It's still really verbose, but depending on how you decided on the acceptable values, that could be worked around.


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •