CondorcetPair<TCandidate extends Comparable> constructor

CondorcetPair<TCandidate extends Comparable>(
  1. TCandidate can1,
  2. TCandidate can2, [
  3. List<RankedBallot<TCandidate>>? ballots
])

Implementation

factory CondorcetPair(
  TCandidate can1,
  TCandidate can2, [
  List<RankedBallot<TCandidate>>? ballots,
]) {
  assert(can1 != can2, 'can1 and can2 must be different');

  if (can1.compareTo(can2) > 0) {
    final temp = can2;
    can2 = can1;
    can1 = temp;
  }

  if (ballots == null) {
    return CondorcetPair._internal(can1, can2, null, null, null);
  } else {
    var firstOverSecond = 0;
    var secondOverFirst = 0;
    var ties = 0;
    for (var b in ballots) {
      final firstIndex = b.rank.indexOf(can1);
      final secondIndex = b.rank.indexOf(can2);

      if (firstIndex < 0) {
        if (secondIndex < 0) {
          // neither candidate is in the ballot
          ties++;
        } else {
          secondOverFirst++;
        }
      } else if (secondIndex < 0) {
        firstOverSecond++;
      } else if (firstIndex < secondIndex) {
        firstOverSecond++;
      } else {
        secondOverFirst++;
      }
    }

    return CondorcetPair._internal(
      can1,
      can2,
      firstOverSecond,
      secondOverFirst,
      ties,
    );
  }
}