You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
mvfront-react/services/majorityJudgment.ts

30 lines
727 B

/**
* A few useful function for dealing with majority judgment
*/
1 year ago
import {MeritProfileInterface} from './type';
/**
* Return the index corresponding to the majority grade
*/
export const getMajorityGrade = (profile: MeritProfileInterface): number => {
1 year ago
const grades = Object.keys(profile).map(k => parseInt(k)).sort()
if (grades.length === 0) {
throw new Error('Merit profile is empty');
}
const numVotes = Object.values(profile).reduce((a, b) => a + b, 0);
1 year ago
let majorityGrade = grades[0];
let accBefore = 0;
1 year ago
for (const grade of grades) {
if (accBefore + profile[grade] > numVotes / 2 - 1e-5) {
return grade;
}
accBefore += profile[grade];
}
1 year ago
return grades[grades.length - 1];
};