gpt4 book ai didi

javascript - 对两个不同的序列使用单个生成器

转载 作者:行者123 更新时间:2023-11-30 13:51:03 24 4
gpt4 key购买 nike

我无法理解为什么我的代码不能正确执行,我使用一个生成器生成两个不同的序列。

function lerp(a, b, perc) {
return a + (b - a) * perc;
};

function check_lerp(a, b) {
if(Math.abs(a - b) > 0.3) return true;
return false;
};

//lerp generator, given a start and end angle generates angles for back-and forth motion.
//start -> end and then end -> start again.
function *lgen(start, end, perc) {
let back = false;
s = start;
e = end;
while(1) {
if(check_lerp(s, e)){
s = lerp(s, e, perc);
yield s;
}
else if(!back) {
back = true;
s = end;
e = start;
}
else break;
}
}

var first = lgen(0, 10, 0.1);
var second = lgen(100, 200, 0.1);

console.log(first.next().value);
console.log(second.next().value);
console.log(first.next().value); //should be between 0 and 10 but is 119 (resumes second.next() val.)

知道发生了什么事吗?提前致谢。

最佳答案

只使用局部变量。未声明的变量是全局的。

function lerp(a, b, perc) {
return a + (b - a) * perc;
};

function check_lerp(a, b) {
if (Math.abs(a - b) > 0.3) return true;
return false;
};

//lerp generator, given a start and end angle generates angles for back-and forth motion.
//start -> end and then end -> start again.
function* lgen(start, end, perc) {
let back = false,
s = start, // declare and initialize
e = end; // declare and initialize
while (1) {
if (check_lerp(s, e)) {
s = lerp(s, e, perc);
yield s;
} else if (!back) {
back = true;
s = end;
e = start;
} else break;
}
}

var first = lgen(0, 10, 0.1);
var second = lgen(100, 200, 0.1);

console.log(first.next().value);
console.log(second.next().value);
console.log(first.next().value); //should be between 0 and 10 but is 119 (resumes second.next() val.)

关于javascript - 对两个不同的序列使用单个生成器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58239551/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com