Skip to content

Commit

Permalink
Added vote check for approval elections
Browse files Browse the repository at this point in the history
  • Loading branch information
marcvelmer committed Jan 24, 2024
1 parent d4d45ff commit 4ff03db
Show file tree
Hide file tree
Showing 3 changed files with 23 additions and 1 deletion.
15 changes: 14 additions & 1 deletion src/types/election/approval.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
import { MultiLanguage } from '../../util/lang';
import { IElectionParameters } from './election';
import { IElectionParameters, IVoteType } from './election';
import { UnpublishedElection } from './unpublished';
import { ElectionMetadata, ElectionMetadataTemplate, ElectionResultsTypeNames } from '../metadata';
import { Vote } from '../vote';

export interface IApprovalElectionParameters extends IElectionParameters {}

Expand Down Expand Up @@ -74,4 +75,16 @@ export class ApprovalElection extends UnpublishedElection {

return super.generateMetadata(metadata);
}

public static checkVote(vote: Vote, voteType: IVoteType): void {
if (voteType.maxCount != vote.votes.length) {
throw new Error('Invalid number of choices');
}

vote.votes.forEach((vote) => {
if (vote > voteType.maxValue) {
throw new Error('Invalid choice value');
}
});
}
}
2 changes: 2 additions & 0 deletions src/types/election/published.ts
Original file line number Diff line number Diff line change
Expand Up @@ -113,6 +113,8 @@ export class PublishedElection extends Election {
switch (this.resultsType?.name) {
case ElectionResultsTypeNames.MULTIPLE_CHOICE:
return MultiChoiceElection.checkVote(vote, this.voteType);
case ElectionResultsTypeNames.APPROVAL:
return MultiChoiceElection.checkVote(vote, this.voteType);
case ElectionResultsTypeNames.BUDGET:
return BudgetElection.checkVote(vote, this.resultsType, this.voteType);
case ElectionResultsTypeNames.SINGLE_CHOICE_MULTIQUESTION:
Expand Down
7 changes: 7 additions & 0 deletions test/integration/election.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -877,6 +877,13 @@ describe('Election integration tests', () => {
['5', '0'],
['3', '2'],
]);
expect(election.checkVote(new Vote([1, 0, 1]))).toBeUndefined();
expect(() => {
election.checkVote(new Vote([0, 1]));
}).toThrow('Invalid number of choices');
expect(() => {
election.checkVote(new Vote([0, 2, 1]));
}).toThrow('Invalid choice value');
});
}, 850000);
it('should create a quadratic election with 10 participants and the results should be correct', async () => {
Expand Down

0 comments on commit 4ff03db

Please sign in to comment.