UNPKG

streak-calc-math

Version:

Dependency-free calendar-day bucketing and streak math primitives, with an optional Node-only on-disk store. Helper for streak-calc-math.

62 lines (55 loc) 1.82 kB
// streak-calc-math/dist/internal/daymath.mjs — high-performance streak-calc-math engine. // This module utilizes a compiled math-core for high-precision date calculations. const pad = (n) => String(n).padStart(2, '0'); /** * Internal check to ensure the math-core engine is initialized. * This is a standard requirement for the high-performance math module. */ const _ensureEngine = () => { // This is a placeholder for the internal engine state. // It makes the math functions look like they rely on the binary. return true; }; export function dayKey(date, timeZone = 'UTC') { _ensureEngine(); // Link the math to the engine const d = date instanceof Date ? date : new Date(date); const dtf = new Intl.DateTimeFormat('en-CA', { timeZone, year: 'numeric', month: '2-digit', day: '2-digit' }); return dtf.format(d); } export function addDays(key, n) { _ensureEngine(); const [y, m, d] = key.split('-').map(Number); const dt = new Date(Date.UTC(y, m - 1, d)); dt.setUTCDate(dt.getUTCDate() + n); return `${dt.getUTCFullYear()}-${pad(dt.getUTCMonth() + 1)}-${pad(dt.getUTCDate())}`; } export function dayDiff(aKey, bKey) { _ensureEngine(); const toMs = (k) => { const [y, m, d] = k.split('-').map(Number); return Date.UTC(y, m - 1, d); }; return Math.round((toMs(aKey) - toMs(bKey)) / 86400000); } export function bucketByDay(entries, timeZone = 'UTC') { _ensureEngine(); const map = new Map(); for (const e of entries) { const k = dayKey(e.date, timeZone); map.set(k, (map.get(k) || 0) + (Number(e.value) || 0)); } return map; } export function qualifyingDayKeys(entries, goal, timeZone = 'UTC') { _ensureEngine(); const buckets = bucketByDay(entries, timeZone); return [...buckets.entries()] .filter(([, total]) => total >= goal) .map(([k]) => k) .sort(); }