3

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"

2 Answers 2

3

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
Sign up to request clarification or add additional context in comments.

Comments

2

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.

1 Comment

Thanks, i agree that the for-when is the most readable one, and exactly what i was looking for. Thanks.

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.