Basically, I want a function I can call which lets me iterate in a bouncing-loop between a range of numbers by a specified increment. I’ve tried way complex solutions with many conditionals but it seems to me this should really be a simple math one-liner no?
I’m having a bit of trouble formulating my question so here is some pseudo coffescript to better explain my goals.
# Pseudo Coffeescript class
Class OscillatingIterator
constructor: ( low, high, increment )->
this.low = low
this.high = high
this.i = increment
iter: ->
### can haz magical math code plz? ###
# Usage
oi = new OscillatingIterator( 1, 5 , 1 )
# outputs
oi.iter() #=> 1
oi.iter() #=> 2
oi.iter() #=> 3
oi.iter() #=> 4
oi.iter() #=> 5
oi.iter() #=> 4
oi.iter() #=> 3
oi.iter() #=> 2
oi.iter() #=> 1
oi.iter() #=> 2
oi.iter() #=> 3
oi.iter() #=> 4
oi.iter() #=> 5
oi.iter() #=> 4
oi.iter() #=> ...
I’ve slightly modified the version written by ori. I think this is a kind of behavior that oscillator should have. Changing the sign of increment to bounce from the bound is only a part of what should be done, because it is good for step = 1 only. Example – oscillator between -2 and 3 with step 2. The code above will give -2, 0, 2, 0, -2, 0, 2 and so on.
I think it should be -2, 0, 2, 2 (1 step from 2 to 3 and 1 step to return), 0, -2, 0 and so on.. The same for (-4,4,3). It should be -4, -1, 2, 3, 0, -3, -1 and so on (the original code will give -4, -1, 2, -1, -4, ..). My suggestion is (I also added one more checkup for the values of the parameters)