基本上,我想要一个可以调用的函数,它可以让我在一系列数字之间的弹跳循环中按指定的增量进行迭代。我已经尝试过使用许多条件的复杂解决方案,但在我看来这真的应该是一个简单的数学单行不是吗?
我在表述我的问题时遇到了一些麻烦,所以这里有一些伪 CoffeeScript 可以更好地解释我的目标。
# 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() #=> ...
最佳答案
我对 ori 编写的版本进行了轻微修改。我认为这是振荡器应该具有的一种行为。将增量的符号更改为从边界反弹只是应该做的一部分,因为它只对 step = 1 有好处。示例 - -2 和 3 之间的振荡器,步骤 2。上面的代码将给出 -2、0、2、0、-2、0、2 等。
我认为它应该是 -2、0、2、2(从 2 到 3 的 1 步和返回的 1 步)、0、-2、0 等等。对于 (-4,4, 3).它应该是 -4、-1、2、3、0、-3、-1 等等(原始代码将给出 -4、-1、2、-1、-4、..)。我的建议是(我还为参数值添加了一个检查)
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;
};
}
关于javascript - 需要数学方面的帮助才能用 CoffeeScript 或 Javascript 编写振荡迭代器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9236379/