Reputation: 2655
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
Reputation: 201513
How about this? I thought 2 patterns for your situation. Please think of this as one of several answers.
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);
}
}
}
doSomething a for a in aList when a.id in (b.id for b in bList)
.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);
});
});
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