0
\$\begingroup\$

This code is used to toggle buttons within a div:

var chosen = {};
var form_name = 'the_div';
function(what) {
   if('number' != typeof what) { // toggle-one
        var el = $(what);
        var name = el.html();
        var ch = ['success','default'];
        if( !chosen[name] ) ch.unshift(ch.pop());
        el.removeClass('btn-' + ch[0]).addClass('btn-' + ch[1]);
        chosen[name] = !chosen[name];
        return;
    }
    var choices = $('#'+form_name).find('div');
    switch(what) { // when toolbar button clicked
        case 1: // select-all
            choices.each(function(idx,el){
                var el = $(el);
                var name = el.html();
                if(!chosen[name]) {
                    el.removeClass('btn-default').addClass('btn-success');
                    chosen[name] = true;
                }
            });
            break;
        case 0: // select-none
            choices.each(function(idx,el){
                var el = $(el);
                var name = el.html();
                if(chosen[name]) {
                    el.removeClass('btn-success').addClass('btn-default');
                    chosen[name] = false;
                }
            });
            break;
        case -1: // select-inverse / toggle-all
            choices.each(function(idx,el){
                var el = $(el);
                var name = el.html();
                var ch = ['success','default'];
                if(!chosen[name]) ch.unshift(ch.pop());
                el.removeClass('btn-'+ch[0]).addClass('btn-'+ch[1]);
                chosen[name] = !chosen[name];
            });
            break;
    }
}

Any suggestion on how to simplify this code?

\$\endgroup\$
1
\$\begingroup\$

Here are some of my suggestions:

  • Declare static things at the top. i.e. var ch = ['success','default']; it is declared twice.
  • Duplicate code should be pulled into functions (see below).
  • Be consistent: el.removeClass('btn-default').addClass('btn-success'); and el.removeClass('btn-'+ch[1]).addClass('btn-'+ch[0]); Either make use of ch or get rid of it (I suggest the first).

Duplicate code:

var el = $(el);
var name = el.html();
var ch = ['success','default'];
if(!chosen[name]) ch.unshift(ch.pop());
el.removeClass('btn-'+ch[0]).addClass('btn-'+ch[1]);
chosen[name] = !chosen[name];

Something like:

var ch = ['success','default'], 
    toggleElement = function (el) {
        var el = $(el),
            name = el.html();

        if(!chosen[name]) ch.unshift(ch.pop());
        el.removeClass('btn-'+ch[0]).addClass('btn-'+ch[1]);
        chosen[name] = !chosen[name];
    };

Your case 0 and case 1 statements could be made into a function as well as they're identical (other than the true/false).

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.