nupes-elections/nupes-elections-front/src/utils.js

103 lines
2.8 KiB
JavaScript

export function getNomZone(typeResultats, zoneInfo) {
if (!zoneInfo.type)
return ""
else if (typeResultats === "france")
return "France"
else if (typeResultats === "region")
return `Région ${zoneInfo.nom}`
else if (typeResultats === "departement")
return `Département ${zoneInfo.nom}`
else if (typeResultats === "circonscription")
return `Circonscription ${zoneInfo.id}`
else if (typeResultats === "commune")
return `Commune ${zoneInfo.nom}`
else if (typeResultats === "bureau_vote")
return zoneInfo.libelle
}
export function trierCandidats(candidats, voix_par_candidat, key = "numero") {
return candidats.toSorted((l1, l2) => {
return (voix_par_candidat[l2[key]] || 0) - (voix_par_candidat[l1[key]] || 0)
})
}
export function regrouperVoix(voixCandidats, candidats, blocs, nuances, dejaGroupesParNuance = false) {
if (!candidats || !voixCandidats || !blocs || !nuances
|| candidats.length === 0 || blocs.length === 0 || nuances.length === 0)
return [{}, {}]
const key = dejaGroupesParNuance ? "code" : "numero"
const parBloc = {}
const parNuance = dejaGroupesParNuance ? voixCandidats : {}
for (let bloc of blocs) {
parBloc[bloc.nom] = 0
}
if (!dejaGroupesParNuance) {
for (let nuance of nuances) {
parNuance[nuance.code] = 0
}
}
for (let candidat of candidats) {
parBloc[candidat.bloc] += voixCandidats[candidat[key]] || 0
if (!dejaGroupesParNuance)
parNuance[candidat.nuance] += voixCandidats[candidat[key]] || 0
}
return [parBloc, parNuance]
}
export function calculerSieges(listes, resultats, seuil = 0.05) {
if (!resultats['voix'])
return {}
const MAX_SIEGES = 81
const sieges = {}
const listesElues = []
let siegesAffectes = 0
let totalVoix = resultats.exprimes
for (let liste of listes) {
const voix = resultats?.voix[liste.numero] ?? 0
if (voix / resultats.exprimes < seuil) {
// Barre des 5 % non franchie
totalVoix -= voix
sieges[liste.numero] = 0
}
else {
listesElues.push(liste)
}
}
if (listesElues.length === 0)
return
for (let liste of listesElues) {
const voix = resultats?.voix[liste.numero] ?? 0
sieges[liste.numero] = Math.floor(MAX_SIEGES * voix / totalVoix)
siegesAffectes += sieges[liste.numero]
}
while (siegesAffectes < MAX_SIEGES) {
// Méthode de la plus forte moyenne pour affecter les sièges restants
let maxMoyenne = 0
let listeElue = null
for (let liste of listesElues) {
if (sieges[liste.numero] < MAX_SIEGES) {
const voix = resultats?.voix[liste.numero] ?? 0
const moyenne = voix / (sieges[liste.numero] + 1)
if (moyenne > maxMoyenne) {
maxMoyenne = moyenne
listeElue = liste
}
}
}
sieges[listeElue.numero]++
siegesAffectes++
}
return sieges
}