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 === 'sib43214@gmail.com' || item.id === 'iva72198@gmail.com')) {
                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.

Dhana
  • 1,618
  • 4
  • 23
  • 39

1 Answers1

2

Use an array or Set instead:

getList(oauth2Client).then(items => {
  const emails = new Set(['sib43214@gmail.com', 'iva72198@gmail.com']);
  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 = ['sib43214@gmail.com', 'iva72198@gmail.com'];
  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)

CertainPerformance
  • 356,069
  • 52
  • 309
  • 320