javascript - for loop variable expressions mathematical manipulating -
i'm writing program in js , im feeling i'm repeating code, not good. i'm trying avoid if else
block has 2 similar for loop
, re-write without if else
using 1 for loop
.
consider this: minimum
has value 0
. maximum
has value 10
. if new_value
less old_value
wanna execute loop minimum
to new_value
, else wanna execute maximum
downto new_value
lets see in action, lets javascript (language-agnostic answers welcome , upvoted -but not grant cookie)
var minimum = 0; var maximum = 10; var old_value = 5; /* var new_value = taken user input whatever ... */ if(new_value<old_value) { for(i=minimum;i<new_value;i++) { // whatever } } else { for(i=maximum;i>new_value;i--) { // whatever } }
i have feeling these 2 for loop
s similar enough written 1 in mathematical approach maybe. have tried bit using absolute values math.abs()
math.max.apply()
had no luck.
i don't want set other helping variables using if else
give appropriate values.
so, whats question: i'm wondering if can rewritten in 1 for ... loop
without being nested in if else
.
a complete solution using built-in js functions will grant cookie.
edit: didn't see original thing not using if/else variables. why not then? go 0 10, using value or 10 minus value depending on conditional.
for(var j = 0; j <= 10; j++) { var = new_value < old_value ? j : 10 - j; // whatever }
assign min, max , increment variables, define them based on if condition , use them in loop:
var old_value = 5, start, end, inc; if(new_value<old_value) { start = 0; end = 10; inc = 1; } else { start = 10; end = 0; inc = -1; } for( = start;i >= start && <= end; += inc) { // whatever }
Comments
Post a Comment