Reputation: 29
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.
Upvotes: 0
Views: 60
Reputation: 370689
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)
Upvotes: 2