Skip to content

Commit

Permalink
Rewrite rank vote merging to avoid modifying the collection mid-itera…
Browse files Browse the repository at this point in the history
…tion.
  • Loading branch information
Kinematics committed Sep 8, 2015
1 parent b942eaf commit de83e7b
Showing 1 changed file with 9 additions and 17 deletions.
26 changes: 9 additions & 17 deletions TallyCore/VoteCounter.cs
Original file line number Diff line number Diff line change
Expand Up @@ -181,34 +181,25 @@ public bool Merge(string fromVote, string toVote, VoteType voteType)

if (voteType == VoteType.Rank)
{
List<KeyValuePair<string, HashSet<string>>> removedVotes = new List<KeyValuePair<string, HashSet<string>>>();
Dictionary<KeyValuePair<string, HashSet<string>>, string> mergedVotes = new Dictionary<KeyValuePair<string, HashSet<string>>, string>();

bool merged = false;
foreach (var vote in votesSet)
{
if (VoteString.CondenseRankVote(vote.Key) == fromVote)
{
string toContent = VoteString.GetVoteContent(toVote, voteType);

string revisedKey = VoteString.ModifyVoteLine(vote.Key, content: toContent);

if (Rename(vote, revisedKey, voteType))
{
removedVotes.Add(vote);
merged = true;
}
mergedVotes.Add(vote, revisedKey);
}
}

if (merged)
foreach (var merge in mergedVotes)
{
foreach (var removed in removedVotes)
{
votesSet.Remove(removed.Key);
}
Rename(merge.Key, merge.Value, VoteType.Rank);
}

return merged;
return mergedVotes.Count > 0;
}


Expand Down Expand Up @@ -333,7 +324,6 @@ public bool Rename(string oldVote, string newVote, VoteType voteType)
return false;
}


/// <summary>
/// Rename a vote.
/// </summary>
Expand All @@ -351,6 +341,7 @@ private bool Rename(KeyValuePair<string, HashSet<string>> vote, string revisedKe
return false;

var votesSet = GetVotesCollection(voteType);
string oldVoteKey = vote.Key;

HashSet<string> votes;
if (votesSet.TryGetValue(revisedKey, out votes))
Expand All @@ -362,10 +353,11 @@ private bool Rename(KeyValuePair<string, HashSet<string>> vote, string revisedKe
votesSet[revisedKey] = vote.Value;
}

votesSet.Remove(oldVoteKey);

return true;
}


/// <summary>
/// Add a supporter to the supplied vote.
/// Adds the vote to the vote list if it didn't already exist.
Expand Down

0 comments on commit de83e7b

Please sign in to comment.