Now it's a pitty you cannot receive a hashmap instead of an array, just to save yourself the task of iterate the elements one by one searching for one.
Well, I think of two techniques for optimizing:
function processTag(total, tag, associatedTicker) {
var foundFlag = false;
TagFactory.retrieveTickerTags('onlyTags').then(function(data) {
console.log('onlyTags data',data);
// Are there are selected Tags:
// Search for tag in tagFactory
var tagIndex=searchTagInArray(data, tag);
// If found, remove tag:
if (tagIndex>=0) {
removeTag(tag, associatedTicker, tagIndex);
}
else {
// Save the tag if not found or there are not selected tags:
if (data.length==0 || total < 3) {
saveTag(tag, associatedTicker);
}
// 3 are already selected, display alert:
else {
displayAlert('failure', 'Only 3 tags can be monitored at a time.');
}
}
});
}
function searchTagInArray(data, tag){
var foundIndex=-1;
for (var i=0; foundIndex<0 && i<data.length; i++) {
if (data[i].term_id === tag.term_id) {
foundIndex = true;
}
}
return foundIndex;
}
And if you can replace the array for a HashMap, you can save the whole searchTagInArray method:
(Assuming retrieveTickerTags returns data as a HashMap of tags indexed by term_id: data={term0: tag0, term1: tag1, term2: tag2...})
function processTag(total, tag, associatedTicker) {
TagFactory.retrieveTickerTags('onlyTags').then(function(data) {
console.log('onlyTags data',data);
// Are there selected Tags:
// Search for tag in tagFactory
var oldTag=data[tag.term_id];
// If found, remove tag:
if (oldTag) {
removeTag(tag, associatedTicker);
}
else {
// Save the tag if not found or there are not selected tags:
if (data.length==0 || total < 3) {
saveTag(tag, associatedTicker);
}
// 3 are already selected, display alert:
else {
displayAlert('failure', 'Only 3 tags can be monitored at a time.');
}
}
});
}