52 lines
1.8 KiB
JavaScript
52 lines
1.8 KiB
JavaScript
|
(() => {
|
||
|
let candidates;
|
||
|
let headerContainer = document.querySelector('.wrapper-power-bar');
|
||
|
headerContainer.insertAdjacentHTML('afterend', `<dialog open style="margin-left: 0;"><table><thead><tr><th>Name</th><th>Votes</th></tr></thead><tbody id="table-body"></tbody></table></dialog>`);
|
||
|
const {
|
||
|
fetch: originalFetch
|
||
|
} = window;
|
||
|
window.fetch = async (...args) => {
|
||
|
let [resource, config] = args;
|
||
|
let response = await originalFetch(resource, config);
|
||
|
if (!response.ok) {
|
||
|
return response;
|
||
|
}
|
||
|
const f = response.url.split('/').pop();
|
||
|
if (f === "metadata.json") {
|
||
|
const metadata = await response.json();
|
||
|
candidates = new Map(metadata.candidates.map((c) => [c.uid, c.fullName]));
|
||
|
} else if (f === "president.json") {
|
||
|
|
||
|
const president = await response.json();
|
||
|
let data = president[0]["state_electionTypes"].map((t) => t.state.officeRaces[0].candidateVotes.map((o) => {
|
||
|
return {
|
||
|
"name": (candidates) ? candidates.get(o.candidate) : o.candidate,
|
||
|
"votes": o.totalVote
|
||
|
};
|
||
|
})).reduce((acc, current) => {
|
||
|
current.forEach((candidate) => {
|
||
|
const existingCandidate = acc.find((c) => c.name === candidate.name);
|
||
|
if (existingCandidate) {
|
||
|
existingCandidate.votes += candidate.votes;
|
||
|
} else {
|
||
|
acc.push(candidate);
|
||
|
}
|
||
|
});
|
||
|
return acc;
|
||
|
}, []);
|
||
|
|
||
|
if (data.length > 0) {
|
||
|
let tableBody = document.getElementById('table-body');
|
||
|
tableBody.innerHTML = '';
|
||
|
data.forEach((row, index) => {
|
||
|
let rowElement = tableBody.insertRow();
|
||
|
let nameCell = rowElement.insertCell();
|
||
|
let votesCell = rowElement.insertCell();
|
||
|
nameCell.textContent = row.name;
|
||
|
votesCell.textContent = row.votes;
|
||
|
});
|
||
|
}
|
||
|
}
|
||
|
return response;
|
||
|
};
|
||
|
})();
|