Reputation: 187
Im still trying to learn CoffeeScript, so im simply asking how you would write this code in a more simple way.
for member in draft.members
if member.email is emailAddress then throw new Meteor.Error 500, "Cannot add member twice"
Upvotes: 3
Views: 2000
Reputation: 19229
You can also use Array#some
, which results in quite simple JS and does not require external libraries :)
emailAlreadyUsed = draft.members.some (m) -> m.email is emailAddress
throw new Meteor.Error 500, 'Cannot add member twice' if emailAlreadyUsed
Upvotes: 3
Reputation:
Step one is making it readable:
for member in draft.members
if member.email is emailAddress
throw new Meteor.Error 500, 'Cannot add member twice'
We can eliminate the if
-expression using when
:
for member in draft.members when member.email is emailAddress
throw new Meteor.Error 500, 'Cannot add member twice'
Please don't write hideous long lines. Remember that if
-expressions can span multiple lines.
As for a complete alternative, you can eliminate the for
-expression if you use Underscore.js or jQuery. Here is an example using Underscore.js (if you prefer jQuery, see $.grep
):
if _.find(draft.members, (m) -> m.email is emailAddress)
throw new Meteor.Error 500, 'Cannot add member twice'
IMO, the for
-expression with when
is most readable.
Upvotes: 2