hey all.. i need a function that would return a previous and next numbers, but only within my numbers range. so, for example, if my range is from 0 to 7, and im on 6 - next should return 7. if im on 7 - next should return 0 (it circled back to it).
same for previous, if im on 0, previous should be 7. I think modulo can be used to figure this out, but cant figure out how. the function should take 3 arguments- current number we are on, maximum number and if we 开发者_如何学Pythonare going back or forward. something like
getPreviousOrNext(0, 7, "next" or "prev" )
thanks!!!
Use modulo..
function getPreviousOrNext(now, max, direction) {
totalOptions = max + 1; //inlcuding 0!
newNumber = now; // If direction is unclear, the number will remain unchanged
if (direction == "next") newNumber = now + 1;
if (direction == "prev") newNumber = now + totalOptions - 1; //One back is same as totalOptions minus one forward
return newNumber % totalOptions;
}
(could be shorter, but this makes it more understandable)
Edit: The "now + totalOptions - 1" prevents us from going into negative numbers (-1 % 7 = -1)
Edit2: Ouch, there was a small error in the code..."If direction is unclear, the number will remain unchanged" was not correct!
Edit3: And for a bonus, this is how I would have written it before reading Code Complete ;-) (assumes it's 'next' whenever it's not 'prev'). This is ugly and beautiful in one :
function getPreviousOrNext(now, max, direction) {
return (now + ((direction=="prev")?max:1)) % (max + 1);
}
is this a homework assignment?
i wouldn't use modulo, a handful of if/ternary statements should be sufficient.
var cycle_range = function (high, current) {
return new function () {
this.next = function () {
return current = (current+1) % (high+1);
};
this.previous = function () {
return current = (current+high) % (high+1);
};
}
};
cycle_range(7, 0).next() // 1
var the_range = cycle_range(7, 0);
the_range.next() // 1
the_range.next() // 2
the_range.previous() //1
the_range.previous() //0
the_range.previous() //7
精彩评论