Reputation: 592
I am new to react and javascript , trying to refactor my below code to fewer lines:
for (const email of processedData) {
if (validateEmail(email)) {
count++;
if (count === 100) {
break;
}
}
}
processedData is a list of emails, tried using reduce but in reduce i could not break once i have count === 100
Thanks
Upvotes: 1
Views: 1382
Reputation: 4020
Array.prototype.some will run a function on your array's element until that function returns true.
Then you can do something like this :
EDIT : single line version of my first suggestion.
var processedData = ["[email protected]", "[email protected]", "[email protected]", "[email protected]", "[email protected]"];
var count = 0;
processedData.some(email => validateEmail(email) && (++count === 2));
function validateEmail(email) {
console.log("validateEmail " + email);
return (email.indexOf(".com") > -1);
}
Upvotes: 4
Reputation: 968
Well, if you just want to have an array with 100 items, then this could help. Apply .filter() on the data array and then slice it to 100.
processedData.filter(email => validateEmail(email)).slice(0,100)
Upvotes: 1
Reputation: 663
How about using below loop?
for(let i=0,count=0; i < processedData.length && count<100; i++){
count+=validateEmail(processedData[i])
}
Upvotes: 0
Reputation: 684
I think... it shoud help, but probably is better way to refactor (as always)
for(const email of processedData){
if(validateEmail(email) && count != 100) count++
}
Upvotes: 0
Reputation: 11940
At least the loop body can be compressed easily:
for(const email of processedData) {
if(validateEmail(email) && ++count === 100) break
}
It would be hard to make it even shorter. >_>
Upvotes: 4