Reputation: 57469
How can I convert this loop to coffeescript?
for (var j = world.m_jointList; j; j = j.m_next) {
drawJoint(j, context);
}
Upvotes: 1
Views: 340
Reputation: 4682
while j = (unless j? then first else j.next)
do stuff
But generally, what's wrong with just writing for
loops with the initialize code as a separate statement, e.g. j=first; while j then ...; j=j.next
?
edit: Or, possibly:
while j = j?.next ? first
do stuff
Upvotes: 2
Reputation: 35253
What's happening in the original:
Javascript has compound for loops. The declaration inside the parenthesis has three expressions: for(x; y; z){...}
.
x
runs once before the loopy
is a condition, tested before each iteration. If it's false the loop will stopz
runs once after every iterationIn this code, you set j = world.m_jointList
, which is the first item in the linked list. The middle part of the for
loop is checking for thruthiness of j;
, and after each iteration j
is set to j.m_next
, which is a pointer to the next object in the chain. It ends when j
evaluates to false (probably undefined
in this case).
To visualize that, world
could look like this:
world = {
m_jointList: {
value: 'head',
m_next: world.foo1
},
foo1: {
value: 'foo',
m_next: world.foo2
},
foo2: {
value: 'foo',
m_next: world.tail
},
tail: {
value: 'foo'
}
}
In reality the items in the list probably don't exist as properties of world
, but this would work the same. Notice that m_next
is undefined in the last object. Sometimes a placeholder value for the tail will be used indicating the end of the chain.
The name m_jointList
is also a bit misleading here because it doesn't actually contain the list, just the first element of it.
This should do it in coffeescript:
j = world.m_jointList
while j then drawJoint(j, context); j = j.m_next
And that would've been a good use of do...while
in javascript:
var j = world.m_jointList
do { drawJoint(j, context) } while (j = j.m_next)
Upvotes: 1
Reputation: 1740
this is the best:
j = world.m_jointList
loop
break if not j
drawJoint j,context
j=j.m_next
it just describes what the for
loop mean.
Upvotes: 0