Search code examples
javascriptjqueryoptimizationprototypejs

How to optimize/avoid switch condition in javascript when seperate function calls are required


I ended up with this code a few minutes ago and it left me wondering whether there would be an elegant way to optimize it into fewer lines, with the optional bonus of perhaps avoiding the switch condition.

        switch(orientation){
            case 'l':
                $('landscapeButton').addClassName('active');
                $('portraitButton').removeClassName('active');
                break;
            default:
                $('landscapeButton').removeClassName('active');
                $('portraitButton').addClassName('active');
        }

Is it possible to further optimize this code? And if yes, how would you accomplish it?

Edit: I should have included some info on which library/libraries i am using. In fact i use both, but in this example i use prototype, as i prefer to use that for dealing with CSS class names. In any case, in my specific case it didn't matter whether the solution was provided in Prototype or jQuery. Thanks to everyone!


Solution

  • For prototypejs:

    If orientation will be 1 or 0, use a function that takes a switch argument to toggle appropriately.

    function safeToggleClass(id, clss, switch) {
        return $(id)[(!!switch ? "add" : "remove") + "ClassName"](clss);
    }
    

    safeToggleClass('landscapeButton', 'active', +orientation);
    safeToggleClass('portraitButton', 'active', !+orientation);
    

    For jQuery:

    jQuery has this switch built in to their toggleClass method.

    $('#landscapeButton').toggleClass('active', +orientation);
    $('#portraitButton').toggleClass('active', !+orientation);