2 ms·
You have to clone from the previous iteration - because in theory, the block itself could modify the loop variable again and that modification gets lost if you
by xg15 6y ago
You have to clone from the previous iteration - because in theory, the block itself could modify the loop variable again and that modification gets lost if you keep cloning from the initial environment.
So your function would produce incorrect results for cases like this:
for (let i = 0; i < 100; i++) {
i += 10;
setTimeout(() => console.log(i), 1000);
}
I think the following should work though:
function FOR(env, cond, incr, block) {
if (cond(env)) {
block(env);
const env2 = {...env};
incr(env2);
FOR(env2, cond, incr, block);
}
}
FOR({i: 0}, s=>(s.i < 8), s=>s.i++, s=>{
setTimeout(() => {
console.log(s.i)
}, 100)
});
And yeah, I agree, it's not really complicated to implement (as long as you don't care about the waste of memory). It was just an unexpected bit of logic at that point.