0

I have some API to launch my project, here is the part of code, I want to ask about

getList(oauth2Client).then(items => {
            for (const item of items) {
              if (item.selected && (item.id === '[email protected]' || item.id === '[email protected]')) {
                promiseArray.push(getEvents(oauth2Client, item.id, item.backgroundColor));
              }
            }

How can i do the if statement without hard code, I mean change those two specific emails to some common use case.

1
  • Is items an array, and is promiseArray empty at the beginning? (if so, the code can be made prettier) Commented Dec 14, 2018 at 7:29

1 Answer 1

2

Use an array or Set instead:

getList(oauth2Client).then(items => {
  const emails = new Set(['[email protected]', '[email protected]']);
  for (const item of items) {
    if (item.selected && emails.has(item.id)) {
      promiseArray.push(getEvents(oauth2Client, item.id, item.backgroundColor));
    }
  }
});

I'd prefer a Set because it has lower complexity, but with an array, use .includes:

getList(oauth2Client).then(items => {
  const emails = ['[email protected]', '[email protected]'];
  for (const item of items) {
    if (item.selected && emails.includes(item.id)) {
      promiseArray.push(getEvents(oauth2Client, item.id, item.backgroundColor));
    }
  }
});

Or, if you want any email address to pass, use a regular expression, something like:

getList(oauth2Client).then(items => {
  const emailRe = /^\w+@[a-z0-9]\.[a-z]+$/i;
  for (const item of items) {
    if (item.selected && emailRe.test(item.id)) {
      promiseArray.push(getEvents(oauth2Client, item.id, item.backgroundColor));
    }
  }
});

(if you want to be even more rigorous, see the regex here)

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks, but I don't need only those '[email protected]', '[email protected]' emails to be correct, i want any email address to be ok to pass.
OK, appreciate your help.

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.