Add index.js

This commit is contained in:
zongor 2024-11-05 08:34:57 -05:00
parent 965b3cbf4c
commit e650c629b7
1 changed files with 52 additions and 0 deletions

52
index.js Normal file
View File

@ -0,0 +1,52 @@
(() => {
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;
};
})();