krz/world-incarceration

An interactive map of world incarceration statistics.

clone: git clone https://gitbay.org/krz/world-incarceration.git

v2: assets/js/ui/controls.js · raw

 1const BTN_IDS  = ["totPop", "perCapita", "women", "juveniles", "occupancy"];
 2const METRIC_KEYS = ["pop",    "rate",      "females", "juveniles", "occupancy"];
 3
 4export function initControls(onMetricChange, onLabelToggle, onReset) {
 5	BTN_IDS.forEach((id, i) => {
 6		const btn = document.getElementById(id);
 7		if (!btn) return;
 8		btn.addEventListener("click", () => {
 9			BTN_IDS.forEach(b => document.getElementById(b)?.classList.remove("active-metric"));
10			btn.classList.add("active-metric");
11			onMetricChange(METRIC_KEYS[i]);
12		});
13	});
14
15	document.querySelector("[data-action='labels']")?.addEventListener("click", e => {
16		e.preventDefault();
17		onLabelToggle();
18	});
19
20	document.querySelector("[data-action='reset']")?.addEventListener("click", e => {
21		e.preventDefault();
22		onReset();
23	});
24}
25
26// Returns [{label, value, alpha3}] top-5 plus a rest-of-world entry.
27export function getTop5(countries, metricKey) {
28	const valid = Object.entries(countries)
29		.filter(([, c]) => typeof c[metricKey] === "number" && !isNaN(c[metricKey]))
30		.sort((a, b) => b[1][metricKey] - a[1][metricKey]);
31
32	const top5 = valid.slice(0, 5).map(([alpha3, c]) => ({
33		label: c.country,
34		value: c[metricKey],
35		alpha3,
36	}));
37
38	const restValue = valid.slice(5).reduce((sum, [, c]) => sum + c[metricKey], 0);
39	if (restValue > 0) {
40		top5.push({ label: "Rest of World", value: restValue, alpha3: null });
41	}
42
43	return top5;
44}
45
46export function formatMetricValue(val, key) {
47	if (val === "--" || val === null || val === undefined || (typeof val === "number" && isNaN(val))) {
48		return "N/A";
49	}
50	if (key === "pop") return Number(val).toLocaleString("en");
51	if (key === "rate") return String(val);
52	if (key === "females" || key === "juveniles" || key === "occupancy") {
53		return (val * 100).toFixed(1) + "%";
54	}
55	return String(val);
56}