Milk
Milk

Reputation: 2655

Iterating matching elements over two arrays in CoffeeScript

I have two lists containing objects of similar type and am looking to operate on the intersecting objects.

Is there a way to simplify this kind of loop using CoffeeScript?

for a in aList
    for b in bList
        if a.id == b.id
            doSomething a

This is the best I can come up with but it's still a bit messy:

doSomething a for a in aList when a.id in (b.id for b in bList)

Any golfing or compilation optimization is appreciated.

Upvotes: 0

Views: 54

Answers (1)

Tanaike
Tanaike

Reputation: 201513

How about this? I thought 2 patterns for your situation. Please think of this as one of several answers.

Pattern 1

The simple way which was written at your script is below.

for a in aList
    for b in bList
        if a.id == b.id
            doSomething a

When this is converted as a comprehension script, that is below.

doSomething b for b in bList when b.id is a.id for a in aList

When both scripts are compiled, the result is the same as follows.

for (i = 0, len = aList.length; i < len; i++) {
  a = aList[i];
  for (j = 0, len1 = bList.length; j < len1; j++) {
    b = bList[j];
    if (a.id === b.id) {
      doSomething(a);
    }
  }
}

Note :

  • This way is faster than your doSomething a for a in aList when a.id in (b.id for b in bList).

Pattern 2

aList.map (a) -> bList.filter (b) -> a.id is b.id && doSomething a

When this script is compiled, the result is as follows.

aList.map(function(a) {
  return bList.filter(function(b) {
    return a.id === b.id && doSomething(a);
  });
});

Note :

  • This way is slower than your doSomething a for a in aList when a.id in (b.id for b in bList).

If this was not useful for you, I'm sorry.

Upvotes: 1

Related Questions