Shawn Mclean
Shawn Mclean

Reputation: 57469

Loops in coffeescript with operations

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

Answers (3)

shesek
shesek

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

Ricardo Tomasi
Ricardo Tomasi

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 loop
  • y is a condition, tested before each iteration. If it's false the loop will stop
  • z runs once after every iteration

In 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

island205
island205

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

Related Questions