Session 23: All-day intelligence layer — schedule, game lines, streaks, hot lists, stat filtering, ParlayAPI dead (1567 tests)
This commit is contained in:
@@ -28,6 +28,7 @@ const TTL = Object.freeze({
|
||||
boxScoreFinal: 24 * 3600,
|
||||
scoreboard: 1 * 3600,
|
||||
bvp: 24 * 3600, // BvP doesn't change mid-day — 24h cache is fine
|
||||
odds: 15 * 60, // Session 23 — book-by-book game lines, 15min
|
||||
});
|
||||
|
||||
function getHost() {
|
||||
@@ -178,10 +179,32 @@ async function getMLBDailyScoreboard(date) {
|
||||
}));
|
||||
}
|
||||
|
||||
/**
|
||||
* getMLBBettingOdds — Tank01's game-level odds feed (book-by-book).
|
||||
* Chrome Claude confirmed this serves LIVE moneylines, run lines, and
|
||||
* totals from bet365 / betmgm / caesars (Session 23). Separate from the
|
||||
* odds-api player-props pipeline; shares the RAPID_API_KEY quota.
|
||||
*
|
||||
* Returns the raw `body` (a map keyed by gameID, each carrying a
|
||||
* per-sportsbook odds object). The gameLines route normalizes it.
|
||||
*/
|
||||
async function getMLBBettingOdds(date) {
|
||||
if (!date) return null;
|
||||
const ymd = String(date).replace(/-/g, '');
|
||||
const data = await fetchWithCache(
|
||||
`/getMLBBettingOdds?gameDate=${ymd}`,
|
||||
`tank01:mlb:odds:${ymd}`,
|
||||
TTL.odds,
|
||||
);
|
||||
if (data === null) return null;
|
||||
return data?.body || data;
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
getMLBBoxScore,
|
||||
getMLBBatterVsPitcher,
|
||||
getMLBDailyScoreboard,
|
||||
getMLBBettingOdds,
|
||||
hasApiKey,
|
||||
__internals: {
|
||||
TTL,
|
||||
|
||||
@@ -0,0 +1,140 @@
|
||||
/**
|
||||
* Hot lists (Session 23).
|
||||
*
|
||||
* Rolling recent-window leaders — but through VYNDR's lens. "Hot" does
|
||||
* NOT mean "highest raw number." It means performing ABOVE the player's
|
||||
* own baseline in the recent window. A 20-PPG player going 28/31/25 is
|
||||
* hot; a 30-PPG player who dropped 28 is not.
|
||||
*
|
||||
* Baseline preference:
|
||||
* 1. explicit `player.seasonAvg[stat]` if supplied
|
||||
* 2. else the player's own games OUTSIDE the recent window (recent vs rest)
|
||||
*
|
||||
* If neither baseline is available (a player with only window-length
|
||||
* history and no season avg) the player is excluded — we can't claim
|
||||
* "trending up" without something to trend against.
|
||||
*
|
||||
* Pure & deterministic. The route supplies cached logs; this does math.
|
||||
*/
|
||||
|
||||
const { __internals } = require('./streaksService');
|
||||
const { nba, mlb, soccer } = __internals;
|
||||
|
||||
// category → accessor fn, per sport. Mirrors STAT_FILTERS categories.
|
||||
const HOT_STATS = {
|
||||
nba: {
|
||||
points: nba.points, rebounds: nba.rebounds, assists: nba.assists,
|
||||
threes: nba.threes, blocks: nba.blocks, steals: nba.steals, pra: nba.pra,
|
||||
},
|
||||
wnba: {
|
||||
points: nba.points, rebounds: nba.rebounds, assists: nba.assists,
|
||||
threes: nba.threes, blocks: nba.blocks, steals: nba.steals,
|
||||
},
|
||||
mlb: {
|
||||
hits: mlb.hits, home_runs: mlb.homeRuns, stolen_bases: mlb.stolenBases,
|
||||
rbis: mlb.rbi, total_bases: mlb.totalBases, strikeouts: mlb.strikeouts,
|
||||
on_base: mlb.onBase,
|
||||
},
|
||||
soccer: {
|
||||
goals: soccer.goals, assists: soccer.assists, shots: soccer.shotsOnTarget,
|
||||
},
|
||||
};
|
||||
|
||||
// Headline stat per sport when the caller asks for 'all'.
|
||||
const DEFAULT_STAT = { nba: 'points', wnba: 'points', mlb: 'hits', soccer: 'goals' };
|
||||
|
||||
const STAT_LABEL = {
|
||||
points: 'pts', rebounds: 'reb', assists: 'ast', threes: '3PM',
|
||||
blocks: 'blk', steals: 'stl', pra: 'PRA',
|
||||
hits: 'H', home_runs: 'HR', stolen_bases: 'SB', rbis: 'RBI',
|
||||
total_bases: 'TB', strikeouts: 'K', on_base: 'OB',
|
||||
goals: 'G', shots: 'SOT',
|
||||
};
|
||||
|
||||
function mean(rows, fn) {
|
||||
if (!rows.length) return 0;
|
||||
return rows.reduce((acc, r) => acc + fn(r), 0) / rows.length;
|
||||
}
|
||||
|
||||
function round1(n) { return Math.round(n * 10) / 10; }
|
||||
|
||||
function resolveStat(sport, stat) {
|
||||
const table = HOT_STATS[sport] || {};
|
||||
if (!stat || stat === 'all') return DEFAULT_STAT[sport] || Object.keys(table)[0] || null;
|
||||
return table[stat] ? stat : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns a ranked list of hot players for one stat.
|
||||
* players = [{ name, playerId, team, games, seasonAvg? }]
|
||||
* opts = { stat, window=7, limit, now, windowDays }
|
||||
*
|
||||
* When rows carry a `date` and `windowDays`+`now` are supplied, the recent
|
||||
* window is date-based; otherwise it's the last `window` games.
|
||||
*/
|
||||
function computeHotList(players, sport, opts = {}) {
|
||||
const key = String(sport || '').toLowerCase();
|
||||
const stat = resolveStat(key, opts.stat);
|
||||
if (!stat || !Array.isArray(players)) return [];
|
||||
const fn = HOT_STATS[key][stat];
|
||||
const window = opts.window && opts.window > 0 ? opts.window : 7;
|
||||
|
||||
const rows = [];
|
||||
for (const p of players) {
|
||||
const games = Array.isArray(p?.games) ? p.games.slice() : [];
|
||||
if (games.length === 0) continue;
|
||||
if (opts.chronological) games.reverse();
|
||||
|
||||
let recent;
|
||||
let rest;
|
||||
if (opts.windowDays && opts.now && games[0]?.date) {
|
||||
const cutoff = opts.now - opts.windowDays * 86_400_000;
|
||||
recent = games.filter((g) => new Date(g.date).getTime() >= cutoff);
|
||||
rest = games.filter((g) => new Date(g.date).getTime() < cutoff);
|
||||
} else {
|
||||
recent = games.slice(0, window);
|
||||
rest = games.slice(window);
|
||||
}
|
||||
if (recent.length === 0) continue;
|
||||
|
||||
const recentAvg = mean(recent, fn);
|
||||
|
||||
// Baseline: explicit season avg, else the player's older games.
|
||||
let baseline = null;
|
||||
const sa = p.seasonAvg && p.seasonAvg[stat];
|
||||
if (sa !== undefined && sa !== null && Number.isFinite(Number(sa))) {
|
||||
baseline = Number(sa);
|
||||
} else if (rest.length > 0) {
|
||||
baseline = mean(rest, fn);
|
||||
}
|
||||
if (baseline === null) continue; // nothing to trend against
|
||||
if (recentAvg <= baseline) continue; // not hot — at or below baseline
|
||||
|
||||
const delta = recentAvg - baseline;
|
||||
rows.push({
|
||||
sport: key,
|
||||
stat,
|
||||
name: p.name || p.player || null,
|
||||
playerId: p.playerId ?? p.id ?? null,
|
||||
team: p.team || null,
|
||||
recentAvg: round1(recentAvg),
|
||||
baseline: round1(baseline),
|
||||
delta: round1(delta),
|
||||
window: recent.length,
|
||||
statLine: `${round1(recentAvg)} ${STAT_LABEL[stat] || stat} over last ${recent.length}`,
|
||||
trendDescription: `+${round1(delta)} above ${round1(baseline)} avg`,
|
||||
});
|
||||
}
|
||||
|
||||
// Rank by how far above baseline (the "trending" signal), then by raw
|
||||
// recent average as the tie-breaker (secondary stat).
|
||||
rows.sort((a, b) => (b.delta - a.delta) || (b.recentAvg - a.recentAvg));
|
||||
const limited = opts.limit && opts.limit > 0 ? rows.slice(0, opts.limit) : rows;
|
||||
return limited.map((r, i) => ({ rank: i + 1, ...r }));
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
computeHotList,
|
||||
resolveStat,
|
||||
__internals: { HOT_STATS, DEFAULT_STAT, mean },
|
||||
};
|
||||
@@ -0,0 +1,95 @@
|
||||
/**
|
||||
* Roster game-log loader (Session 23).
|
||||
*
|
||||
* Streaks and hot lists both need "every player's recent game log" — but
|
||||
* VYNDR caches logs per-player on demand (`gamelogs:{sport}:{player}:{n}`)
|
||||
* as the grading flow touches them. There's no roster-wide pull, and we
|
||||
* will NOT add API calls to build one (free/cheap-only session).
|
||||
*
|
||||
* So we read what's ALREADY cached:
|
||||
* 1. A precomputed roster blob `rosterlogs:{sport}` if a prefetch wrote
|
||||
* one (fast path — a single read).
|
||||
* 2. Otherwise SCAN the per-player `gamelogs:{sport}:*` keys and assemble
|
||||
* a roster from whatever's warm.
|
||||
*
|
||||
* Everything here is Redis-only (free) and defensive — any failure yields
|
||||
* an empty roster, never a throw. An empty roster is a valid state: the
|
||||
* streaks/hot-list panels simply render nothing while other layers carry
|
||||
* the slate.
|
||||
*/
|
||||
|
||||
const { cacheGet, getRedisClient, isDegraded } = require('../utils/redis');
|
||||
|
||||
const SCAN_COUNT = 200;
|
||||
const MAX_KEYS = 600; // safety cap so a huge cache can't stall a request
|
||||
|
||||
/**
|
||||
* Parse a player display name out of a gamelogs key.
|
||||
* Key shape: `gamelogs:{sport}:{playerName}:{count}` — playerName may
|
||||
* itself contain colons in theory, so split off the known head/tail.
|
||||
*/
|
||||
function playerFromKey(key, sport) {
|
||||
const prefix = `gamelogs:${sport}:`;
|
||||
if (!key.startsWith(prefix)) return null;
|
||||
const rest = key.slice(prefix.length);
|
||||
const lastColon = rest.lastIndexOf(':');
|
||||
if (lastColon === -1) return rest;
|
||||
return rest.slice(0, lastColon);
|
||||
}
|
||||
|
||||
async function scanGameLogKeys(sport) {
|
||||
if (isDegraded && isDegraded()) return [];
|
||||
const redis = getRedisClient();
|
||||
if (!redis || typeof redis.scan !== 'function') return [];
|
||||
const match = `gamelogs:${sport}:*`;
|
||||
const keys = [];
|
||||
let cursor = '0';
|
||||
try {
|
||||
do {
|
||||
const [next, batch] = await redis.scan(cursor, 'MATCH', match, 'COUNT', SCAN_COUNT);
|
||||
cursor = next;
|
||||
for (const k of batch) {
|
||||
if (!keys.includes(k)) keys.push(k);
|
||||
if (keys.length >= MAX_KEYS) return keys;
|
||||
}
|
||||
} while (cursor !== '0');
|
||||
} catch (err) {
|
||||
console.warn('[rosterLogs] scan failed:', err.message);
|
||||
return keys;
|
||||
}
|
||||
return keys;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns [{ name, playerId, team, games }] for a sport. Dedupes players
|
||||
* (the highest game-count key wins) so one player isn't double-counted
|
||||
* across `:10` / `:20` cache variants.
|
||||
*/
|
||||
async function loadRosterLogs(sport) {
|
||||
const key = String(sport || '').toLowerCase();
|
||||
if (!key) return [];
|
||||
|
||||
// Fast path — a prefetched roster blob.
|
||||
const blob = await cacheGet(`rosterlogs:${key}`);
|
||||
if (Array.isArray(blob) && blob.length > 0) return blob;
|
||||
|
||||
const keys = await scanGameLogKeys(key);
|
||||
if (keys.length === 0) return [];
|
||||
|
||||
const byPlayer = new Map();
|
||||
for (const k of keys) {
|
||||
const name = playerFromKey(k, key);
|
||||
if (!name) continue;
|
||||
const games = await cacheGet(k);
|
||||
if (!Array.isArray(games) || games.length === 0) continue;
|
||||
const existing = byPlayer.get(name);
|
||||
if (!existing || games.length > existing.games.length) {
|
||||
const playerId = games[0]?.playerId ?? games[0]?.player_id ?? null;
|
||||
const team = games[0]?.team ?? games[0]?.teamAbv ?? null;
|
||||
byPlayer.set(name, { name, playerId, team, games });
|
||||
}
|
||||
}
|
||||
return Array.from(byPlayer.values());
|
||||
}
|
||||
|
||||
module.exports = { loadRosterLogs, __internals: { playerFromKey, scanGameLogKeys } };
|
||||
@@ -0,0 +1,182 @@
|
||||
/**
|
||||
* Schedule service (Session 23).
|
||||
*
|
||||
* Today's game schedule from FREE ESPN scoreboards. NO odds-api credits
|
||||
* burned. Cache-aside: reads `schedule:{sport}:{date}` from Redis first;
|
||||
* on a miss it fetches the ESPN scoreboard directly (the same free
|
||||
* endpoint the PM2 pollers hit every 60s), normalizes, caches, returns.
|
||||
*
|
||||
* This dual path is deliberate. The pollers warm the cache during game
|
||||
* hours, but the endpoint must NEVER be empty just because a poller is
|
||||
* down or off-hours — so it self-heals by fetching ESPN on a cache miss.
|
||||
*
|
||||
* Everything here is free. The only paid/quota'd layer (Tank01 game
|
||||
* lines, odds-api props) is checked separately via the hasGameLines /
|
||||
* hasOdds flags, which read OTHER caches without ever triggering a fetch.
|
||||
*/
|
||||
|
||||
const axios = require('axios');
|
||||
const { cacheGet, cacheSet } = require('../utils/redis');
|
||||
const { SPORT_CONFIG } = require('../config/sports');
|
||||
|
||||
function getSportConfig(sport) {
|
||||
return SPORT_CONFIG[String(sport || '').toLowerCase()] || null;
|
||||
}
|
||||
|
||||
const HTTP_TIMEOUT_MS = 10_000;
|
||||
const SCHEDULE_TTL = 60; // 60s — mirrors poller cadence; live scores stay fresh
|
||||
const STALE_TTL = 6 * 3600; // stale-while-error fallback
|
||||
|
||||
/**
|
||||
* Today's date in ET as YYYY-MM-DD. Sports days roll over on ET, not UTC,
|
||||
* so a late west-coast game still counts as "today" past midnight UTC.
|
||||
*/
|
||||
function todayET() {
|
||||
const fmt = new Intl.DateTimeFormat('en-CA', {
|
||||
timeZone: 'America/New_York',
|
||||
year: 'numeric', month: '2-digit', day: '2-digit',
|
||||
});
|
||||
return fmt.format(new Date()); // en-CA → YYYY-MM-DD
|
||||
}
|
||||
|
||||
/**
|
||||
* Normalize one ESPN scoreboard event into VYNDR's schedule shape.
|
||||
* Defensive throughout — ESPN omits fields freely (no venue for neutral
|
||||
* sites, no broadcast until close to tip). A missing field becomes null,
|
||||
* never a throw.
|
||||
*/
|
||||
function normalizeEvent(ev) {
|
||||
if (!ev) return null;
|
||||
const comp = ev.competitions?.[0] || {};
|
||||
const competitors = comp.competitors || [];
|
||||
const home = competitors.find((c) => c.homeAway === 'home') || competitors[0] || {};
|
||||
const away = competitors.find((c) => c.homeAway === 'away') || competitors[1] || {};
|
||||
|
||||
const team = (c) => ({
|
||||
name: c?.team?.displayName || c?.team?.name || c?.team?.shortDisplayName || null,
|
||||
abbreviation: c?.team?.abbreviation || null,
|
||||
});
|
||||
|
||||
const score = (c) => {
|
||||
const n = Number(c?.score);
|
||||
return Number.isFinite(n) ? n : 0;
|
||||
};
|
||||
|
||||
const state = ev.status?.type?.state || comp.status?.type?.state || null; // pre|in|post
|
||||
const hasScore = state === 'in' || state === 'post';
|
||||
|
||||
// Broadcast: ESPN scatters this across competitions[].broadcasts and
|
||||
// geoBroadcasts. Take the first network name we can find.
|
||||
let broadcast = null;
|
||||
const bcasts = comp.broadcasts || [];
|
||||
if (bcasts[0]?.names?.[0]) broadcast = bcasts[0].names[0];
|
||||
else if (comp.geoBroadcasts?.[0]?.media?.shortName) broadcast = comp.geoBroadcasts[0].media.shortName;
|
||||
|
||||
return {
|
||||
id: String(ev.id),
|
||||
homeTeam: team(home),
|
||||
awayTeam: team(away),
|
||||
gameTime: ev.date || comp.date || null,
|
||||
status: state,
|
||||
score: hasScore ? { home: score(home), away: score(away) } : null,
|
||||
venue: comp.venue?.fullName || null,
|
||||
broadcast,
|
||||
hasOdds: false, // filled by enrichFlags
|
||||
hasGameLines: false, // filled by enrichFlags
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Fetch + normalize the ESPN scoreboard for a sport. Free endpoint.
|
||||
*/
|
||||
async function fetchScheduleFromEspn(sport) {
|
||||
const cfg = getSportConfig(sport);
|
||||
if (!cfg || !cfg.espnScoreboard) return null;
|
||||
const res = await axios.get(cfg.espnScoreboard, { timeout: HTTP_TIMEOUT_MS });
|
||||
const events = res.data?.events || [];
|
||||
return events.map(normalizeEvent).filter(Boolean);
|
||||
}
|
||||
|
||||
/**
|
||||
* Cache-aside schedule read. Returns an array of normalized games
|
||||
* (possibly empty — empty is a valid "no games today", not an error).
|
||||
* Returns null only when the sport is unknown / unsupported.
|
||||
*/
|
||||
async function getSchedule(sport, date) {
|
||||
const cfg = getSportConfig(sport);
|
||||
if (!cfg || !cfg.espnScoreboard) return null;
|
||||
const key = `schedule:${sport}:${date}`;
|
||||
|
||||
const cached = await cacheGet(key);
|
||||
if (cached !== null) return cached;
|
||||
|
||||
try {
|
||||
const games = await fetchScheduleFromEspn(sport);
|
||||
if (Array.isArray(games)) {
|
||||
await cacheSet(key, games, SCHEDULE_TTL);
|
||||
await cacheSet(`${key}:stale`, games, STALE_TTL);
|
||||
return games;
|
||||
}
|
||||
return [];
|
||||
} catch (err) {
|
||||
console.warn(`[schedule] ESPN fetch failed for ${sport}:`, err.message);
|
||||
const stale = await cacheGet(`${key}:stale`);
|
||||
return stale !== null ? stale : [];
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Per-game enrichment: set hasOdds / hasGameLines by peeking at the OTHER
|
||||
* caches. Reads only — never triggers a fetch, never burns quota. The
|
||||
* odds-api props cache and the Tank01 game-lines cache are date-keyed
|
||||
* (one blob per sport+date), so a single read tells us whether ANY game
|
||||
* that day has data; we apply it to every game in the slate.
|
||||
*
|
||||
* A future refinement could match per-game, but the date-level flag is
|
||||
* the honest signal today: "props exist for this slate" / "lines exist
|
||||
* for this slate".
|
||||
*/
|
||||
async function enrichFlags(sport, date, games) {
|
||||
if (!Array.isArray(games) || games.length === 0) return games;
|
||||
const ymd = String(date).replace(/-/g, '');
|
||||
|
||||
// odds-api props cache — oddsService writes `odds:{sport}:{utcDate}`
|
||||
// as `{ updated_at, props, spreads }`. The slate `date` is ET, so try
|
||||
// the ET key first then the UTC key (they differ only past midnight).
|
||||
const utcDate = new Date().toISOString().split('T')[0];
|
||||
const oddsCache =
|
||||
(await cacheGet(`odds:${sport}:${date}`)) ??
|
||||
(await cacheGet(`odds:${sport}:${utcDate}`)) ??
|
||||
(await cacheGet(`odds:${sport}`));
|
||||
const hasOdds = hasPropsData(oddsCache);
|
||||
|
||||
// Tank01 game-lines cache — adapters write tank01:{sport}:odds:{ymd}.
|
||||
const linesCache = await cacheGet(`tank01:${sport}:odds:${ymd}`);
|
||||
const hasGameLines = hasLinesData(linesCache);
|
||||
|
||||
return games.map((g) => ({ ...g, hasOdds, hasGameLines }));
|
||||
}
|
||||
|
||||
function hasPropsData(cache) {
|
||||
if (!cache) return false;
|
||||
if (Array.isArray(cache)) return cache.length > 0;
|
||||
if (Array.isArray(cache.props)) return cache.props.length > 0;
|
||||
if (Array.isArray(cache.games)) return cache.games.length > 0;
|
||||
if (typeof cache === 'object') return Object.keys(cache).length > 0;
|
||||
return false;
|
||||
}
|
||||
|
||||
function hasLinesData(cache) {
|
||||
if (!cache) return false;
|
||||
const body = cache.body || cache;
|
||||
if (Array.isArray(body)) return body.length > 0;
|
||||
if (typeof body === 'object') return Object.keys(body).length > 0;
|
||||
return false;
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
getSchedule,
|
||||
enrichFlags,
|
||||
todayET,
|
||||
__internals: { normalizeEvent, fetchScheduleFromEspn, hasPropsData, hasLinesData },
|
||||
};
|
||||
@@ -0,0 +1,253 @@
|
||||
/**
|
||||
* Streaks engine (Session 23).
|
||||
*
|
||||
* Computes player streaks from cached game-log data. Everything analyzed
|
||||
* through VYNDR's lens — not "Wemby 31 PPG" but "Wemby on a 4-game 28+
|
||||
* scoring streak." A streak is a CONSECUTIVE run of recent games meeting
|
||||
* a threshold; we count from the most recent game backward and stop at
|
||||
* the first miss.
|
||||
*
|
||||
* Pure & deterministic. `computePlayerStreaks` operates on one player's
|
||||
* game array; `computeStreaks` fans out across a roster and returns a
|
||||
* flat, sorted, optionally stat-filtered list. NO API calls live here —
|
||||
* the route layer supplies cached logs.
|
||||
*
|
||||
* Game logs are expected MOST-RECENT-FIRST (index 0 = latest). Pass
|
||||
* `{ chronological: true }` to reverse oldest-first input.
|
||||
*/
|
||||
|
||||
// ---- defensive numeric field reader -------------------------------------
|
||||
function num(row, ...keys) {
|
||||
if (!row) return 0;
|
||||
for (const k of keys) {
|
||||
if (row[k] !== undefined && row[k] !== null && row[k] !== '') {
|
||||
const n = Number(row[k]);
|
||||
if (Number.isFinite(n)) return n;
|
||||
}
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
// NBA/WNBA stat accessors — tolerate the several field spellings the
|
||||
// Python stats service and Tank01 use.
|
||||
const nba = {
|
||||
points: (r) => num(r, 'points', 'pts', 'PTS'),
|
||||
rebounds: (r) => num(r, 'rebounds', 'reb', 'REB', 'totReb'),
|
||||
assists: (r) => num(r, 'assists', 'ast', 'AST'),
|
||||
threes: (r) => num(r, 'threes', 'threes_made', 'fg3m', 'tptfgm', 'threePointersMade'),
|
||||
blocks: (r) => num(r, 'blocks', 'blk', 'BLK'),
|
||||
steals: (r) => num(r, 'steals', 'stl', 'STL'),
|
||||
fgPct: (r) => {
|
||||
const pct = num(r, 'fg_pct', 'fgPct', 'fieldGoalPct');
|
||||
if (pct > 0) return pct > 1 ? pct / 100 : pct; // accept 0–1 or 0–100
|
||||
const m = num(r, 'fgm', 'field_goals_made');
|
||||
const a = num(r, 'fga', 'field_goals_attempted');
|
||||
return a > 0 ? m / a : 0;
|
||||
},
|
||||
};
|
||||
nba.pra = (r) => nba.points(r) + nba.rebounds(r) + nba.assists(r);
|
||||
nba.doubleCount = (r) =>
|
||||
[nba.points(r), nba.rebounds(r), nba.assists(r), nba.steals(r), nba.blocks(r)]
|
||||
.filter((v) => v >= 10).length;
|
||||
|
||||
const mlb = {
|
||||
hits: (r) => num(r, 'hits', 'H', 'h'),
|
||||
homeRuns: (r) => num(r, 'homeRuns', 'home_runs', 'HR', 'hr'),
|
||||
stolenBases: (r) => num(r, 'stolenBases', 'stolen_bases', 'SB', 'sb'),
|
||||
rbi: (r) => num(r, 'rbi', 'RBI'),
|
||||
walks: (r) => num(r, 'walks', 'baseOnBalls', 'BB', 'bb'),
|
||||
hbp: (r) => num(r, 'hitByPitch', 'hbp', 'HBP'),
|
||||
totalBases: (r) => num(r, 'totalBases', 'total_bases', 'TB'),
|
||||
strikeouts: (r) => num(r, 'strikeOuts', 'strikeouts', 'pitcherK', 'K', 'so'),
|
||||
inningsPitched: (r) => num(r, 'inningsPitched', 'ip', 'IP'),
|
||||
earnedRuns: (r) => num(r, 'earnedRuns', 'er', 'ER'),
|
||||
};
|
||||
mlb.onBase = (r) => mlb.hits(r) + mlb.walks(r) + mlb.hbp(r);
|
||||
mlb.isQualityStart = (r) => mlb.inningsPitched(r) >= 6 && mlb.earnedRuns(r) <= 3;
|
||||
|
||||
const nfl = {
|
||||
passTd: (r) => num(r, 'passTD', 'passing_touchdowns', 'pass_td'),
|
||||
rushTd: (r) => num(r, 'rushTD', 'rushing_touchdowns', 'rush_td'),
|
||||
recTd: (r) => num(r, 'recTD', 'receiving_touchdowns', 'rec_td'),
|
||||
rushYds:(r) => num(r, 'rushYds', 'rushing_yards', 'rush_yards'),
|
||||
recYds: (r) => num(r, 'recYds', 'receiving_yards', 'rec_yards'),
|
||||
ints: (r) => num(r, 'interceptions', 'int', 'passInt'),
|
||||
};
|
||||
nfl.anyTd = (r) => nfl.passTd(r) + nfl.rushTd(r) + nfl.recTd(r);
|
||||
|
||||
const soccer = {
|
||||
goals: (r) => num(r, 'goals', 'G'),
|
||||
assists: (r) => num(r, 'assists', 'A'),
|
||||
shotsOnTarget: (r) => num(r, 'shotsOnTarget', 'shots_on_target', 'sot'),
|
||||
goalsConceded: (r) => num(r, 'goalsConceded', 'goals_conceded', 'ga'),
|
||||
minutes: (r) => num(r, 'minutes', 'min', 'MIN'),
|
||||
};
|
||||
|
||||
// ---- streak specs -------------------------------------------------------
|
||||
// Each spec: { key, category, threshold, label, value, mode }.
|
||||
// value(row) → number; the game counts toward the streak when value >= threshold.
|
||||
// mode 'consecutive' (default) counts the run from the latest game.
|
||||
// mode 'rate' marks "hot" when the mean over the last `window` games >= threshold.
|
||||
const SPECS = {
|
||||
nba: [
|
||||
{ key: 'points_25', category: 'points', collapse: 'points', threshold: 25, label: '25+ pts', value: nba.points },
|
||||
{ key: 'points_20', category: 'points', collapse: 'points', threshold: 20, label: '20+ pts', value: nba.points },
|
||||
{ key: 'assists_8', category: 'assists', collapse: 'assists', threshold: 8, label: '8+ ast', value: nba.assists },
|
||||
{ key: 'assists_6', category: 'assists', collapse: 'assists', threshold: 6, label: '6+ ast', value: nba.assists },
|
||||
{ key: 'rebounds_10',category: 'rebounds', collapse: 'rebounds', threshold: 10, label: '10+ reb', value: nba.rebounds },
|
||||
{ key: 'rebounds_8', category: 'rebounds', collapse: 'rebounds', threshold: 8, label: '8+ reb', value: nba.rebounds },
|
||||
{ key: 'threes_4', category: 'threes', collapse: 'threes', threshold: 4, label: '4+ threes', value: nba.threes },
|
||||
{ key: 'threes_3', category: 'threes', collapse: 'threes', threshold: 3, label: '3+ threes', value: nba.threes },
|
||||
{ key: 'blocks_2', category: 'blocks', threshold: 2, label: '2+ blk', value: nba.blocks },
|
||||
{ key: 'steals_2', category: 'steals', threshold: 2, label: '2+ stl', value: nba.steals },
|
||||
{ key: 'pra_40', category: 'pra', threshold: 40, label: '40+ PRA', value: nba.pra },
|
||||
{ key: 'double_double', category: 'all', threshold: 2, label: 'double-double', value: nba.doubleCount, noun: 'double-double' },
|
||||
{ key: 'triple_double', category: 'all', threshold: 3, label: 'triple-double', value: nba.doubleCount, noun: 'triple-double' },
|
||||
{ key: 'hot_shooter', category: 'points', threshold: 0.5, label: 'hot shooter (FG% > 50%)', value: nba.fgPct, mode: 'rate', window: 5 },
|
||||
],
|
||||
// WNBA shares NBA's stat layout (no PRA/triple-double headline emphasis,
|
||||
// but the specs are harmless if a player never hits them).
|
||||
wnba: null, // filled below = nba minus the rate spec quirks
|
||||
mlb: [
|
||||
{ key: 'hit_streak', category: 'hits', collapse: 'hits', threshold: 1, label: 'hit', value: mlb.hits },
|
||||
{ key: 'multi_hit', category: 'hits', collapse: 'hits', threshold: 2, label: 'multi-hit', value: mlb.hits },
|
||||
{ key: 'hr_streak', category: 'home_runs', threshold: 1, label: 'HR', value: mlb.homeRuns },
|
||||
{ key: 'sb_streak', category: 'stolen_bases', threshold: 1, label: 'SB', value: mlb.stolenBases },
|
||||
{ key: 'rbi_streak', category: 'rbis', threshold: 1, label: 'RBI', value: mlb.rbi },
|
||||
{ key: 'onbase_streak',category: 'on_base', threshold: 1, label: 'on-base', value: mlb.onBase },
|
||||
{ key: 'tb_streak', category: 'total_bases', threshold: 2, label: '2+ total bases', value: mlb.totalBases },
|
||||
{ key: 'k_streak', category: 'strikeouts', threshold: 7, label: '7+ K', value: mlb.strikeouts },
|
||||
{ key: 'qs_streak', category: 'strikeouts', threshold: 1, label: 'quality start', value: (r) => (mlb.isQualityStart(r) ? 1 : 0) },
|
||||
],
|
||||
nfl: [
|
||||
{ key: 'td_streak', category: 'touchdowns', threshold: 1, label: 'TD', value: nfl.anyTd },
|
||||
{ key: 'multi_td', category: 'touchdowns', threshold: 2, label: 'multi-TD', value: nfl.anyTd },
|
||||
{ key: 'rush_100', category: 'rushing_yards', threshold: 100, label: '100-yd rushing', value: nfl.rushYds },
|
||||
{ key: 'rec_100', category: 'receiving_yards', threshold: 100, label: '100-yd receiving', value: nfl.recYds },
|
||||
{ key: 'clean_qb', category: 'interceptions', threshold: 1, label: 'INT-free', value: (r) => (nfl.ints(r) === 0 ? 1 : 0) },
|
||||
],
|
||||
soccer: [
|
||||
{ key: 'goal_streak', category: 'goals', threshold: 1, label: 'goal', value: soccer.goals },
|
||||
{ key: 'assist_streak', category: 'assists', threshold: 1, label: 'assist', value: soccer.assists },
|
||||
{ key: 'sot_streak', category: 'shots', threshold: 1, label: 'shot-on-target', value: soccer.shotsOnTarget },
|
||||
{ key: 'clean_sheet', category: 'saves', threshold: 1, label: 'clean sheet',
|
||||
value: (r) => (soccer.minutes(r) > 0 && soccer.goalsConceded(r) === 0 ? 1 : 0) },
|
||||
],
|
||||
};
|
||||
SPECS.wnba = SPECS.nba;
|
||||
|
||||
function specsFor(sport) {
|
||||
return SPECS[String(sport || '').toLowerCase()] || [];
|
||||
}
|
||||
|
||||
// ---- core streak math ---------------------------------------------------
|
||||
function consecutiveRun(games, valueFn, threshold) {
|
||||
let run = 0;
|
||||
for (const g of games) {
|
||||
if (valueFn(g) >= threshold) run += 1;
|
||||
else break;
|
||||
}
|
||||
return run;
|
||||
}
|
||||
|
||||
function rateOverWindow(games, valueFn, window) {
|
||||
const slice = games.slice(0, window);
|
||||
if (slice.length < window) return { value: 0, count: slice.length };
|
||||
const sum = slice.reduce((acc, g) => acc + valueFn(g), 0);
|
||||
return { value: sum / slice.length, count: slice.length };
|
||||
}
|
||||
|
||||
/**
|
||||
* Minimum run length to surface a streak. A "1-game streak" is just a
|
||||
* stat line, not a streak — require at least 2 to count as VYNDR signal,
|
||||
* except double/triple-double which are notable at any length >= 2.
|
||||
*/
|
||||
const MIN_STREAK = 2;
|
||||
|
||||
function describe(spec, run) {
|
||||
if (spec.noun) return `${run}-game ${spec.noun} streak`;
|
||||
if (spec.mode === 'rate') return spec.label;
|
||||
return `${run}-game ${spec.label} streak`;
|
||||
}
|
||||
|
||||
/**
|
||||
* All streaks for ONE player. Returns the strongest streak per stat
|
||||
* CATEGORY (so a player with a 20+ and a 25+ points streak surfaces only
|
||||
* the more impressive one) — keeps the feed signal-dense.
|
||||
*/
|
||||
function computePlayerStreaks(player, sport, opts = {}) {
|
||||
const specs = specsFor(sport);
|
||||
let games = Array.isArray(player?.games) ? player.games.slice() : [];
|
||||
if (opts.chronological) games.reverse();
|
||||
if (games.length === 0) return [];
|
||||
|
||||
const found = [];
|
||||
for (const spec of specs) {
|
||||
if (spec.mode === 'rate') {
|
||||
const { value, count } = rateOverWindow(games, spec.value, spec.window);
|
||||
if (count >= spec.window && value >= spec.threshold) {
|
||||
found.push(makeStreak(player, sport, spec, spec.window, value));
|
||||
}
|
||||
continue;
|
||||
}
|
||||
const run = consecutiveRun(games, spec.value, spec.threshold);
|
||||
if (run >= MIN_STREAK) found.push(makeStreak(player, sport, spec, run));
|
||||
}
|
||||
|
||||
// Collapse tiered specs (e.g. 25+ and 20+ points) to one entry per
|
||||
// collapse group — prefer the MORE IMPRESSIVE streak (higher threshold),
|
||||
// tie-broken by the longer run. Non-tiered specs each have a unique
|
||||
// collapse key, so they pass through untouched.
|
||||
const best = new Map();
|
||||
for (const s of found) {
|
||||
const cur = best.get(s._collapse);
|
||||
if (!cur ||
|
||||
s.threshold > cur.threshold ||
|
||||
(s.threshold === cur.threshold && s.currentStreak > cur.currentStreak)) {
|
||||
best.set(s._collapse, s);
|
||||
}
|
||||
}
|
||||
return Array.from(best.values()).map(({ _collapse, ...rest }) => rest);
|
||||
}
|
||||
|
||||
function makeStreak(player, sport, spec, run, rateValue) {
|
||||
return {
|
||||
sport,
|
||||
player: player.name || player.player || null,
|
||||
playerId: player.playerId ?? player.id ?? null,
|
||||
team: player.team || null,
|
||||
type: spec.key,
|
||||
category: spec.category,
|
||||
threshold: spec.threshold,
|
||||
currentStreak: run,
|
||||
rate: rateValue ?? null,
|
||||
description: describe(spec, run),
|
||||
active: true,
|
||||
_collapse: spec.collapse || spec.key, // internal — stripped before return
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Fan out across a roster. `players` = [{ name, playerId, team, games }].
|
||||
* Returns a flat list sorted by streak length desc, optionally narrowed
|
||||
* to a single stat category and capped at `limit`.
|
||||
*/
|
||||
function computeStreaks(players, sport, opts = {}) {
|
||||
if (!Array.isArray(players)) return [];
|
||||
const stat = opts.stat && opts.stat !== 'all' ? String(opts.stat).toLowerCase() : null;
|
||||
let all = [];
|
||||
for (const p of players) {
|
||||
all = all.concat(computePlayerStreaks(p, sport, opts));
|
||||
}
|
||||
if (stat) all = all.filter((s) => s.category === stat);
|
||||
all.sort((a, b) => b.currentStreak - a.currentStreak);
|
||||
if (opts.limit && opts.limit > 0) all = all.slice(0, opts.limit);
|
||||
return all;
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
computeStreaks,
|
||||
computePlayerStreaks,
|
||||
specsFor,
|
||||
__internals: { consecutiveRun, rateOverWindow, nba, mlb, nfl, soccer, MIN_STREAK },
|
||||
};
|
||||
Reference in New Issue
Block a user