UNPKG

highest-averages

Version:

Zero-dependency and extensible set of highest averages methods for allocating seats in a parliament. ### Install ```shell npm i highest-averages ``` ### Pure Example - Define the candidates with their vote ```typescript const a = new Candidate('A', 200) c

48 lines (47 loc) 1.68 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.HighestAverage = void 0; const candidate_result_1 = require("./models/candidate_result"); require("./extensions/array_extensions"); class HighestAverage { divisor; candidates = []; seat = 0; constructor(divisor) { this.divisor = divisor; } withSeat(seat) { this.seat = seat; return this; } withCandidates(candidates) { this.candidates.clear(); candidates.forEach(candidate => this.candidates.push(candidate)); return this; } apply() { const totalVote = this.candidates.sumOf(candidate => candidate.vote); const candidateResults = this.candidates.map(candidate => new candidate_result_1.CandidateResult(candidate, totalVote)); const dividedVote = (candidateResult) => candidateResult.candidate.vote / this.divisor.next(candidateResult.seat); let selected = 0; while (this.seat !== selected) { const selectableCandidates = candidateResults .filter(candidateResult => candidateResult.selectable()); if (selectableCandidates.length > 1) { selectableCandidates .reduce((x, y) => dividedVote(x) > dividedVote(y) ? x : y) .select(); selected++; } else if (selectableCandidates.length === 1) { selectableCandidates[0].select(); selected++; } else { break; } } return candidateResults; } } exports.HighestAverage = HighestAverage;