diff --git a/addons/majority_judgment/MajorityJudgmentPoll.gd b/addons/majority_judgment/MajorityJudgmentPoll.gd index 2d65a47..ef7894d 100644 --- a/addons/majority_judgment/MajorityJudgmentPoll.gd +++ b/addons/majority_judgment/MajorityJudgmentPoll.gd @@ -38,6 +38,8 @@ export(Array, Resource) var candidates:Array setget set_candidates, get_candidat # Array of MajorityJudgmentJudgments +# If you mutate this property directly and not through add_judgment(), +# remember to update the memoization cache as well with update_participants_index() export(Array, Resource) var judgments:Array setget set_judgments, get_judgments @@ -115,6 +117,9 @@ func set_judgments(__judgments:Array) -> void: func add_judgment(judgment:MajorityJudgmentJudgment) -> void: if not judgments: judgments = Array() + if not judgment.candidate in self.candidates: + printerr("Judgment Candidate is not in the Poll!") + return for i in range(judgments.size()): var existing_judgment = judgments[i] if ( @@ -124,6 +129,7 @@ func add_judgment(judgment:MajorityJudgmentJudgment) -> void: ): judgments[i] = judgment return + update_participants_index(judgment.participant) judgments.append(judgment) @@ -159,6 +165,42 @@ func tally() -> MajorityJudgmentPollTally: return tallier.tally(self) +func get_or_create_participant(identifier:String) -> MajorityJudgmentParticipant: + var known_participants = get_participants_index() + if not known_participants.has(identifier): + known_participants[identifier] = MajorityJudgmentParticipant.make(identifier) + return known_participants[identifier] + + +# Memoization of expensive computation +var __participants_index := Dictionary() # id => Participant + + +func get_participants_index(): + if __participants_index.empty(): + rebuild_participants_index() + return __participants_index + + +func rebuild_participants_index(): + for participant in get_participants(): + assert( + not __participants_index.has(participant.name), + "Participants index should be consistent: names should be unique." + ) + __participants_index[participant.name] = participant + + +func update_participants_index(participant:MajorityJudgmentParticipant): + var identifier = participant.name + if not __participants_index.has(identifier): + __participants_index[identifier] = participant + assert( + __participants_index[identifier] == participant, + "Participants index should be consistent." + ) + + func get_participants() -> Array: var participants := Array() for judgment in judgments: