Skip to content

Instantly share code, notes, and snippets.

@quickredfox
Created February 10, 2012 23:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save quickredfox/1793937 to your computer and use it in GitHub Desktop.
Save quickredfox/1793937 to your computer and use it in GitHub Desktop.
Problem I cannot solve, should be simple math for someone...
function oscillator(low, high, inc) {
// basic test for illegal parameters
if (low > high || inc < 0 || 2 * (high - low) < inc)
return function() { return NaN; };
var curr = low;
return function() {
var ret = curr;
curr += inc;
if (curr > high || curr < low)
{
curr = inc>0 ? 2 * high - curr: 2 * low - curr;
inc = -inc;
};
return ret;
};
}
function oscillator(low, high, increment) {
// basic test for illegal parameters
if (low > high || increment < 0)
return function() { return NaN; };
var curr = low;
return function() {
var ret = curr;
curr += increment;
// if the next number will exceed the boundaries, reverse the increment
if (curr + increment > high || curr + increment < low)
increment = -increment;
return ret;
};
}
# Pseudo Coffeescript class
Class OscillatingIterator
constructor: ( low, high, increment )->
this.low = low
this.high = high
this.i = increment
iterate: ->
### can haz magical math code plz? ###
# Usage
oi = new OscillatingIterator( 1, 10 , 1 )
oi.iterate() #=> 1
oi.iterate() #=> 2
oi.iterate() #=> 3
oi.iterate() #=> 4
oi.iterate() #=> 5
oi.iterate() #=> 6
oi.iterate() #=> 7
oi.iterate() #=> 8
oi.iterate() #=> 9
oi.iterate() #=> 10
oi.iterate() #=> 9
oi.iterate() #=> 8
oi.iterate() #=> 7
oi.iterate() #=> 6
oi.iterate() #=> 5
oi.iterate() #=> 4
oi.iterate() #=> 3
oi.iterate() #=> 2
oi.iterate() #=> 1
oi.iterate() #=> 2
oi.iterate() #=> 3
oi.iterate() #=> etc...
# V1
class OscillatingIterator
constructor: ( @min, @max, @incr )->
@index = 0
iterate: ->
@index+=@incr*( @dir = if @index >= @max and @dir isnt -1 then -1 else if @index<=@min and @dir isnt +1 then +1 else @dir )
@quickredfox
Copy link
Author

solution #1 has no math. A conditional approach.

And it's totally broken with values like min: -9, max: 9 , incr: 1

Works only with careful consideration of values passed.

@ph
Copy link

ph commented Feb 11, 2012

Je suis a l'hopital pour ma fille, pourquoi tu utilises pas le modulo pour ca?
Je peux checker quand je reviens.

@quickredfox
Copy link
Author

@ph No big rush, was just poking you in a very complex way! I'm actually logging all this for meself

@quickredfox
Copy link
Author

for more on ori-via-stackoverflow.js see http://stackoverflow.com/a/9236626/261114

@quickredfox
Copy link
Author

I ended up using cheery's tweaked version of Ori's http://stackoverflow.com/a/9238879/261114

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment