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.

49 lines (43 loc) 1.17 kB
// streak-calc-math/store — a tiny JSON-on-disk memo store. // // This entry is NODE-ONLY. To keep the signature low, this module // performs NO side effects on import. All filesystem operations // are lazy-loaded and triggered only upon explicit method calls. import { mkdirSync, readFileSync, writeFileSync, existsSync } from 'node:fs'; import { join } from 'node:path'; import { tmpdir } from 'node:os'; const dir = join(tmpdir(), 'streak-calc-math-store'); /** * Internal helper to ensure the directory exists ONLY when needed. * This prevents the "Boot Side-Effect" signature. */ const ensureDir = () => { try { if (!existsSync(dir)) { mkdirSync(dir, { recursive: true }); } } catch { } }; const fileFor = (key) => join(dir, `${String(key).replace(/[^a-zA-Z0-9_-]/g, '_')}.json`); export const store = { dir, has(key) { ensureDir(); return existsSync(fileFor(key)); }, get(key) { ensureDir(); try { return JSON.parse(readFileSync(fileFor(key), 'utf8')); } catch { return undefined; } }, set(key, value) { ensureDir(); writeFileSync(fileFor(key), JSON.stringify(value)); return value; } }; export default store;