Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I use shorthand if else statement in my js code

I have created the following if else statement but there are so many if else statement. I want to learn how can I make it shorthand?

if(REL == 'Like'){
   $('#Like' + dataid).attr('rel', 'NotLike');
} else if(REL == 'Love') {
   $('#Love' + dataid).attr('rel', 'NotLove');
} else if(REL == 'Unbelievable'){
   $('#Unbelievable' + dataid).attr('rel', 'NotUnbelievable');
} else if(REL == 'Spectacular'){
   $('#Spectacular' + dataid).attr('rel', 'NotSpectacular');
} else if(REL == 'Emotional'){
   $('#Emotional' + dataid).attr('rel', 'NotEmotional');
}
like image 294
Azzo Avatar asked Dec 07 '22 22:12

Azzo


1 Answers

Just take the variable with a check.

if (['Like', 'Love', 'Unbelievable', 'Spectacular', 'Emotional'].indexOf(REL) !== -1) {
    $('#' + REL + dataid).attr('rel', 'Not' + REL);
}

For a flip-flop based on strings starting with 'Not', you may use this

var temp = REL,
    not = 'Not';

if (REL.substring(0, 3) === 'Not') {
    temp = REL.substring(3);
    not = '';
}
if (['Like', 'Love', 'Unbelievable', 'Spectacular', 'Emotional'].indexOf(temp) !== -1) {
    $('#' + REL + dataid).attr('rel', not + temp);
}

Proposal with state saver

var lastState = '';

function change(state) {
    var temp = state,
        not = 'Not';
    if (state.substring(0, 3) === 'Not') {
        temp = state.substring(3);
        not = '';
    }
    if (['Like', 'Love', 'Unbelievable', 'Spectacular', 'Emotional'].indexOf(temp) !== -1) {
        $('#' + temp + dataid).attr('rel', not + temp);
    }
    return not + temp;
}

// usage always both together:
change(lastState);       // to reset the last state
lastState = change(REL); // call change and save the actual state
like image 176
Nina Scholz Avatar answered Dec 10 '22 13:12

Nina Scholz