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?

Jamal
35.2k13 gold badges134 silver badges238 bronze badges
asked Jan 15, 2015 at 13:06
\$\endgroup\$

1 Answer 1

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).

answered Jan 15, 2015 at 13:21
\$\endgroup\$

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.