From 1804adb9b3bbf54bf03a704459934f61ba635ff7 Mon Sep 17 00:00:00 2001 From: g-but <41178744+g-but@users.noreply.github.com> Date: Mon, 11 May 2026 15:32:30 +0200 Subject: [PATCH] refactor(dry): extract computeStreak helper in habits.ts MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The 7-line streak loop appeared twice — once using HABIT_HISTORY_DAYS as the bound (listHabitsForToday) and once using a dynamic days param (getHabitHeatmapData). Extracted to a private computeStreak(dates, maxDays) function eliminating the duplication. Co-Authored-By: Claude Sonnet 4.6 --- src/db/queries/habits.ts | 27 +++++++++++++-------------- 1 file changed, 13 insertions(+), 14 deletions(-) diff --git a/src/db/queries/habits.ts b/src/db/queries/habits.ts index cc674aaea..0081fb05c 100644 --- a/src/db/queries/habits.ts +++ b/src/db/queries/habits.ts @@ -34,6 +34,17 @@ function isDueToday(frequency: HabitFrequency): boolean { return true; } +function computeStreak(dates: Set, maxDays: number): number { + let streak = 0; + for (let i = 0; i < maxDays; i++) { + const d = new Date(); + d.setDate(d.getDate() - i); + if (dates.has(toLocalDateStr(d))) streak++; + else break; + } + return streak; +} + export function scheduledDays(frequency: HabitFrequency, days: number): number { let count = 0; for (let i = 0; i < days; i++) { @@ -94,13 +105,7 @@ export async function getTodayHabits(userId: string): Promise return dueHabits.map((h) => { const dates = byHabit.get(h.id) ?? new Set(); const doneToday = dates.has(today); - let streak = 0; - for (let i = 0; i < HABIT_HISTORY_DAYS; i++) { - const d = new Date(); - d.setDate(d.getDate() - i); - if (dates.has(toLocalDateStr(d))) streak++; - else break; - } + const streak = computeStreak(dates, HABIT_HISTORY_DAYS); return { id: h.id, title: h.title, frequency: h.frequency, sortOrder: h.sortOrder, doneToday, streak }; }); } @@ -193,13 +198,7 @@ export async function getAllHabitsWithHistory(userId: string, days = HABIT_HISTO return allHabits.map((h) => { const dates = byHabit.get(h.id) ?? new Set(); - let streak = 0; - for (let i = 0; i < days; i++) { - const d = new Date(); - d.setDate(d.getDate() - i); - if (dates.has(toLocalDateStr(d))) streak++; - else break; - } + const streak = computeStreak(dates, days); return { id: h.id, title: h.title,