krz/world-incarceration
An interactive map of world incarceration statistics.
clone: git clone https://gitbay.org/krz/world-incarceration.git
main: assets/js/ui/compare.js · raw
1let _pendingResult = false;
2
3export function initCompare(countries) {
4 const opts = Object.entries(countries)
5 .sort((a, b) => a[1].country.localeCompare(b[1].country))
6 .map(([key, val]) => `<option value="${key}">${val.country}</option>`)
7 .join("");
8
9 document.getElementById("compare-select-1").innerHTML = opts;
10 document.getElementById("compare-select-2").innerHTML = opts;
11
12 document.getElementById("compare-go-btn").addEventListener("click", () => {
13 const k1 = document.getElementById("compare-select-1").value;
14 const k2 = document.getElementById("compare-select-2").value;
15
16 if (k1 === k2) {
17 document.getElementById("compare-alert").innerHTML =
18 "<div class='alert alert-danger'>Please select two different countries.</div>";
19 return;
20 }
21 document.getElementById("compare-alert").innerHTML = "";
22 _prepareResult(countries[k1], countries[k2]);
23 _pendingResult = true;
24 const cm = document.getElementById("compareModal");
25 (bootstrap.Modal.getInstance(cm) || new bootstrap.Modal(cm)).hide();
26 });
27
28 // Show result modal only after compareModal finishes hiding
29 document.getElementById("compareModal").addEventListener("hidden.bs.modal", () => {
30 if (_pendingResult) {
31 _pendingResult = false;
32 const rm = document.getElementById("compareResultModal");
33 (bootstrap.Modal.getInstance(rm) || new bootstrap.Modal(rm)).show();
34 }
35 });
36}
37
38function _prepareResult(c1, c2) {
39 document.getElementById("compare-result-c1").textContent = c1.country;
40 document.getElementById("compare-result-c2").textContent = c2.country;
41
42 const rows = [
43 ["Prison Population", _fmt(c1.pop, "pop"), _fmt(c2.pop, "pop")],
44 ["Rate per 100,000", _fmt(c1.rate, "rate"), _fmt(c2.rate, "rate")],
45 ["Females", _fmt(c1.females, "pct"), _fmt(c2.females, "pct")],
46 ["Juveniles", _fmt(c1.juveniles, "pct"), _fmt(c2.juveniles, "pct")],
47 ["Occupancy", _fmt(c1.occupancy, "pct"), _fmt(c2.occupancy, "pct")],
48 ["Government", _fmtGov(c1.government), _fmtGov(c2.government)],
49 ];
50
51 document.getElementById("compare-result-body").innerHTML = rows
52 .map(([label, v1, v2]) =>
53 `<tr><td><b>${label}</b></td><td>${v1}</td><td>${v2}</td></tr>`
54 )
55 .join("");
56}
57
58function _fmt(val, type) {
59 if (val === "--" || val === null || val === undefined || (typeof val === "number" && isNaN(val))) {
60 return "<span class='text-danger'>N/A</span>";
61 }
62 if (type === "pop") return Number(val).toLocaleString("en");
63 if (type === "rate") return String(val);
64 if (type === "pct") return (val * 100).toFixed(2) + " %";
65 return String(val);
66}
67
68function _fmtGov(val) {
69 return (!val || val === "--") ? "<span class='text-danger'>N/A</span>" : val;
70}