1

I have this code:

log.error(r.reason) for r in results when r.state == 'rejected'

which translates into:

var r, _i, _len, _results;
_results = [];
for (_i = 0, _len = results.length; _i < _len; _i++) {
  r = results[_i];
  if (r.state === 'rejected') {
    _results.push(log.error(r.reason));
  }
}
return _results;

I do not need to accumulate the results of log.error, I just need to print an error for each appropriate element of the array. How is this done in coffeescript?

1 Answer 1

2

Almost every statement in CoffeeScript is an expression. For loops, this implies accumulating the result of each iteration in an array. If you do not want that behavior, you must explicitly add a return statement:

log.error(r.reason) for r in results when r.state == 'rejected'; return

In addition, in order to answer to your question title: "invoke function for each element in array" if your JS runtime supports the array function forEach, this is an alternative way to apply a function on every array item:

results.forEach (item) -> log.error item.reason if item.state == 'rejected'
Sign up to request clarification or add additional context in comments.

3 Comments

thanks. map is what I am trying to avoid. because map collects the results of each function application.
Why would you use map when you're iterating rather than mapping? Wouldn't results.filter(...).forEach(...) make more sense if you're doing it with iterators?
@muistooshort I was editing my answer in that direction when you posted your comment. Of course forEach is the right answer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.