Re:Elevator Saga – An elevator programming game
by lloydatkinson on Saturday June 12, 2021 @06:37PM
(#27487986)
What am I doing wrong?
It only seems to run for the second elevator rather than both of them?
[ Parent
| on HN ]
Re:Elevator Saga – An elevator programming game
by mercora on Saturday June 12, 2021 @06:56PM
(#27488110)
i likely ran into the same or a related issue. i dont know much about javascript though.
for(var i = 0; i < elevators.length; i++) {
elevators[i].on("idle", function() {
for(var j = 0; j < floors.length; j++) {
elevators[i].goToFloor(j);
}
})
}
it only works for "i < 1" and then only the second elevator moves... its kinda sad as i immediately enjoyed playing ...
Re:Elevator Saga – An elevator programming game
by garaetjjte on Saturday June 12, 2021 @07:16PM
(#27488251)
I think this was discussed there: https://news.ycombinator.com/item?id=8933979
Re:Elevator Saga – An elevator programming game
by mercora on Saturday June 12, 2021 @07:22PM
(#27488293)
this did indeed help understanding and fixing the issue.
Re:Elevator Saga – An elevator programming game
by davnicwil on Saturday June 12, 2021 @07:51PM
(#27488460)
Just in case this is interesting, a potentially more elegant way to solve this with modern JS is to use 'for(let i' instead of 'for(var i'.
The reason is that 'let' gives 'i' 'block scope', meaning that each iteration of the loop block gets its own scope so that 'i' isn't overwritten each time, and each function you declare captures the value of 'i' at the time it was declared.
In other words - the way you originally expected 'var' to behave is how 'let' behaves!
Re:Elevator Saga – An elevator programming game
by pazqo on Sunday June 13, 2021 @09:20AM
(#27492344)
You should be able to accomplish the same with elevators.forEach((elevator) => {})
Re:Elevator Saga – An elevator programming game
by lloydatkinson on Monday June 14, 2021 @03:53AM
(#27500335)
It could, but favouring FP I'd use for..of for imperative loops where I need to do side-effects, or use .map which is nicer anyway.
Re:Elevator Saga – An elevator programming game
by emiphil on Saturday June 12, 2021 @09:47PM
(#27489077)
for (elevator ... Like that is making a new global variable called elevator which is getting overwritten on the next loop. You need to for(const elevator... (or let).
The other thread is the same answer but for a slightly different case
Re:Elevator Saga – An elevator programming game
by umvi on Saturday June 12, 2021 @09:41PM
(#27489061)
Should be `for (let elevator of elevators)`
Re:Elevator Saga – An elevator programming game
by lloydatkinson on Sunday June 13, 2021 @03:45AM
(#27490645)
Oh my god you’re right, oops. I wouldn’t normally make that mistake but no IDE and coding at night apparently isn’t a good mix!