Files

43 lines
1.8 KiB
JavaScript
Raw Permalink Normal View History

/* Robot Clash - online ranking. The server computes it from the online saves (fame only changes through
server-booked fights), so the client only reads: GET /api/ranks, polled while a board is open.
DOM-free; RC.Ranking.rank is a pure function (Node-testable).
2026-11-18 15:18:38 +01:00
const rank = RC.Ranking(net);
if (rank.enabled) {
const sub = rank.watch(rows => draw(rows)); // { close() } rows best first, refreshed every 15 s
const rows = await rank.once(20);
2026-11-18 15:18:38 +01:00
}
RC.Ranking.rank(data, n) // [{uid,name,fame,flag}] or { key: {...} } -> sorted array, bad names out, capped */
2026-11-18 15:18:38 +01:00
(function (root) {
'use strict';
const RC = (root.RC = root.RC || {});
const Kit = root.Kit || {};
const bad = s => (Kit.badName ? Kit.badName(s) : false);
const POLL = 15000;
2026-11-18 15:18:38 +01:00
RC.Ranking = function (net) {
const enabled = !!(net && net.enabled);
const fetchRows = async n => RC.Ranking.rank(await net.api('GET', '/api/ranks?n=' + (n || 20)), n);
return {
enabled,
2026-11-18 15:18:38 +01:00
watch(cb, n) {
if (!enabled) { cb([]); return { close() {} }; }
let alive = true;
const tick = () => fetchRows(n).then(rows => { if (alive) cb(rows); });
tick();
const timer = setInterval(tick, POLL);
return { close() { alive = false; clearInterval(timer); } };
2026-11-18 15:18:38 +01:00
},
once: n => (enabled ? fetchRows(n) : Promise.resolve([])),
2026-11-18 15:18:38 +01:00
};
};
RC.Ranking.rank = function (data, n = 20) {
const list = Array.isArray(data) ? data.map(v => Object.assign({ key: v.uid }, v))
: Object.entries(data || {}).map(([key, v]) => Object.assign({ key }, v));
const rows = list.filter(v => v && typeof v.name === 'string' && typeof v.fame === 'number' && !bad(v.name));
2026-11-18 15:18:38 +01:00
rows.sort((a, b) => b.fame - a.fame || (b.ts || 0) - (a.ts || 0));
return rows.slice(0, n);
};
})(typeof window !== 'undefined' ? window : globalThis);