Daniele Vrut
Daniele Vrut

Reputation: 2873

One line coffeescript "return if" iterating an array

This is my code (not working)

return monitor if (monitor.uuid is $scope.selectedMonitor) for monitor in $scope.monitors

I want to return monitor if the if is true and I'm trying to do in one single line. Is it possibile?

Upvotes: 0

Views: 154

Answers (1)

phenomnomnominal
phenomnomnominal

Reputation: 5515

You could use the when keyword:

getSelectedMonitor = ->
  return monitor for monitor in $scope.monitors when monitor.uuid is $scope.selectedMonitor

This generates the following JS:

var getSelectedMonitor = function() {
  var monitor, _i, _len, _ref;
  _ref = $scope.monitors;
  for (_i = 0, _len = _ref.length; _i < _len; _i++) {
    monitor = _ref[_i];
    if (monitor.uuid === $scope.selectedMonitor) {
      return monitor;
    }
  }
};

Upvotes: 2

Related Questions