HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavascriptModerate

Animating one of three boxes based on a form value

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
threeboxesanimatingvalueonebasedform

Problem

Is there a better way to do this without using if or case statements?

var val = ui.value,
$box = $('#message');
switch(true) {
  case (val > 50):
    $box.hide();
    animations.animateBox($box.html('you have chosen XN'));                        
    break;
  case (val < 50):
    $box.hide().delay(300);
    animations.animateBox($box.html('you have chosen VN'));
    break;
  default:
    $box.hide();
    animations.animateBox($box.html('you have chosen PN'));
}

Solution

This completely replaces your switch statement by using inline if statements conditional operator:

$box.hide().delay(val  50 ? 'XN' : (val < 50 ? 'VN' : 'PN');
animations.animateBox($box.html('you have chosen ' + s));


the first line could be replaced by these two arguably more readable lines that omit the call to delay() function when not applicable:

$box.hide();
val < 50 && $box.delay(300);


Since @GregGuida pointed out that this code is less readable I suppose I can make it more readable by better formatting it. And I'll use the suggestion of replacing the first line with two of them:

$box.hide();

// only delay animation when value  50 ? 'XN' :
       (val < 50 ? 'VN' :
                   'PN');
// set HTML
animations.animateBox($box.html('you have chosen ' + s));


Same code but visually less chaotic (even without comments it would look less chaotic) and much much more readable. At least much more readable than OP's original code. That I'm sure of. Readability is of course an argumentative disposition. But I'll leave that to others.

Code Snippets

$box.hide().delay(val < 50 ? 300 : 0);
var s = val > 50 ? 'XN' : (val < 50 ? 'VN' : 'PN');
animations.animateBox($box.html('you have chosen ' + s));
$box.hide();
val < 50 && $box.delay(300);
$box.hide();

// only delay animation when value < 50
val < 50 && $box.delay(300);

var s = val > 50 ? 'XN' :
       (val < 50 ? 'VN' :
                   'PN');
// set HTML
animations.animateBox($box.html('you have chosen ' + s));

Context

StackExchange Code Review Q#7076, answer score: 18

Revisions (0)

No revisions yet.