Reputation: 3706
Here's my function that is supposed to validate a name so that there is no duplicates:
function validateBucketName(){
var counter = 1;
var validated = false;
var suggestedName = "Bucket " + (vm.buckets.length + counter);
if(vm.buckets.length === 0) return suggestedName;
while(!validated){
var foundIndex = vm.buckets.findIndex(function (bucket) {
return bucket.name === suggestedName;
});
if(foundIndex === -1){
validated = true;
} else {
counter++;
suggestedName = "Bucket " + (vm.buckets.length + counter);
}
}
return suggestedName;
}
I am getting the pretty common error, that I am aware of how to deal with in for
loops, but can't figure out how to do that with the while
loop. Can someone have a look at this?
Ps. This is probably very inefficient way of trying to make sure no duplicate names exist. If you have a suggestion for how to make that better feel free to comment.
Upvotes: 0
Views: 424
Reputation: 33726
You don't need the validate
variable, just use while(true)
because you're going to get the missing suggestedName
.
When this condition if (foundIndex === -1)
is true return the suggestedName
.
Look this code snippet with those modifications:
function validateBucketName() {
var counter = 1;
var suggestedName = "Bucket " + (vm.buckets.length + counter);
if (vm.buckets.length === 0) return suggestedName;
var compare = function(bucket) {
return bucket.name === suggestedName;
};
while (true) {
if (vm.buckets.findIndex(compare) === -1) {
return suggestedName;
else
suggestedName = "Bucket " + (vm.buckets.length + (counter++));
}
return suggestedName;
}
Upvotes: 1