Download src/lib/spaced-repetition.ts from NAP1320/RotNot: direct link, hf CLI and curl.
- Browser
- Download file 6.55 kB
-
https://huggingface.co/spaces/NAP1320/RotNot/resolve/main/src/lib/spaced-repetition.ts
- Command line
-
hf download hf://spaces/NAP1320/RotNot/src/lib/spaced-repetition.ts
-
curl -L -o spaced-repetition.ts https://huggingface.co/spaces/NAP1320/RotNot/resolve/main/src/lib/spaced-repetition.ts
6.55 kB
| import { prisma } from "@/lib/db"; | |
| import { Prisma } from "@prisma/client"; | |
| // --------------------------------------------------------------------------- | |
| // Constants | |
| // --------------------------------------------------------------------------- | |
| /** | |
| * Review intervals in milliseconds, indexed by stage (0-5). | |
| * Stage 0 = newly added (first review due in 1 day). | |
| * Stages 1-5 represent increasing mastery intervals. | |
| */ | |
| export const REVIEW_INTERVALS_MS: readonly number[] = [ | |
| 1 * 24 * 60 * 60 * 1000, // Stage 0 β 1: 1 day | |
| 3 * 24 * 60 * 60 * 1000, // Stage 1 β 2: 3 days | |
| 7 * 24 * 60 * 60 * 1000, // Stage 2 β 3: 7 days | |
| 14 * 24 * 60 * 60 * 1000, // Stage 3 β 4: 14 days | |
| 30 * 24 * 60 * 60 * 1000, // Stage 4 β 5: 30 days | |
| ] as const; | |
| /** Maximum stage (fully retained) */ | |
| export const MAX_STAGE = 5; | |
| /** Score threshold (0-1) to advance to the next stage */ | |
| export const PASS_THRESHOLD = 0.6; | |
| /** XP multiplier for spaced repetition reviews (reduced from normal) */ | |
| export const REVIEW_XP_MULTIPLIER = 0.5; | |
| // --------------------------------------------------------------------------- | |
| // Pure logic (testable, no DB) | |
| // --------------------------------------------------------------------------- | |
| /** | |
| * Calculate the next review date based on the current stage. | |
| * If at MAX_STAGE, returns null (fully retained β no more reviews needed). | |
| */ | |
| export function getNextReviewDate( | |
| stage: number, | |
| fromDate: Date = new Date(), | |
| ): Date | null { | |
| if (stage >= MAX_STAGE) return null; | |
| const intervalMs = REVIEW_INTERVALS_MS[stage] ?? REVIEW_INTERVALS_MS[REVIEW_INTERVALS_MS.length - 1]; | |
| return new Date(fromDate.getTime() + intervalMs); | |
| } | |
| /** | |
| * Determine the new stage after a review based on the score. | |
| * Pass (>= threshold): advance one stage (capped at MAX_STAGE). | |
| * Fail (< threshold): reset to stage 1 (not 0 β they've seen it before). | |
| */ | |
| export function computeNewStage(currentStage: number, score: number): number { | |
| if (score >= PASS_THRESHOLD) { | |
| return Math.min(currentStage + 1, MAX_STAGE); | |
| } | |
| return 1; // Reset to stage 1 on failure | |
| } | |
| /** | |
| * Determine if a spaced repetition item is due for review. | |
| */ | |
| export function isDue(nextReviewAt: Date, now: Date = new Date()): boolean { | |
| return nextReviewAt.getTime() <= now.getTime(); | |
| } | |
| /** | |
| * Get a human-readable label for the current stage. | |
| */ | |
| export function stageLabel(stage: number): string { | |
| switch (stage) { | |
| case 0: return "New"; | |
| case 1: return "Learning"; | |
| case 2: return "Reviewing"; | |
| case 3: return "Strengthening"; | |
| case 4: return "Almost There"; | |
| case 5: return "Retained β"; | |
| default: return "Unknown"; | |
| } | |
| } | |
| /** | |
| * Get the interval label for the next review. | |
| */ | |
| export function intervalLabel(stage: number): string { | |
| if (stage >= MAX_STAGE) return "Complete"; | |
| const ms = REVIEW_INTERVALS_MS[stage]; | |
| const days = Math.round(ms / (24 * 60 * 60 * 1000)); | |
| return days === 1 ? "1 day" : `${days} days`; | |
| } | |
| // --------------------------------------------------------------------------- | |
| // DB operations | |
| // --------------------------------------------------------------------------- | |
| /** | |
| * Add a taught topic to the spaced repetition queue. | |
| * Called when a user clicks "I Don't Know This" and completes the teach flow. | |
| * If the topic already exists in the queue, it's a no-op (idempotent). | |
| */ | |
| export async function addToReviewQueue(params: { | |
| userId: number; | |
| topicId: string; | |
| topic: string; | |
| domain: string; | |
| difficulty: string; | |
| }): Promise<{ created: boolean }> { | |
| const { userId, topicId, topic, domain, difficulty } = params; | |
| const now = new Date(); | |
| const nextReviewAt = getNextReviewDate(0, now)!; | |
| try { | |
| await prisma.spacedRepetitionItem.create({ | |
| data: { | |
| userId, | |
| topicId, | |
| topic, | |
| domain, | |
| difficulty, | |
| stage: 0, | |
| nextReviewAt, | |
| createdAt: now, | |
| }, | |
| }); | |
| return { created: true }; | |
| } catch (e) { | |
| // Unique constraint violation β already in queue | |
| if ( | |
| e instanceof Prisma.PrismaClientKnownRequestError && | |
| e.code === "P2002" | |
| ) { | |
| return { created: false }; | |
| } | |
| throw e; | |
| } | |
| } | |
| /** | |
| * Get all review items that are due for a user. | |
| * Excludes items at MAX_STAGE (fully retained). | |
| */ | |
| export async function getDueReviews( | |
| userId: number, | |
| now: Date = new Date(), | |
| limit: number = 10, | |
| ) { | |
| return prisma.spacedRepetitionItem.findMany({ | |
| where: { | |
| userId, | |
| stage: { lt: MAX_STAGE }, | |
| nextReviewAt: { lte: now }, | |
| }, | |
| orderBy: { nextReviewAt: "asc" }, | |
| take: limit, | |
| }); | |
| } | |
| /** | |
| * Get a summary of a user's spaced repetition items. | |
| */ | |
| export async function getReviewSummary(userId: number, now: Date = new Date()) { | |
| const items = await prisma.spacedRepetitionItem.findMany({ | |
| where: { userId }, | |
| orderBy: { nextReviewAt: "asc" }, | |
| }); | |
| const due = items.filter((i) => i.stage < MAX_STAGE && i.nextReviewAt <= now); | |
| const upcoming = items.filter( | |
| (i) => i.stage < MAX_STAGE && i.nextReviewAt > now, | |
| ); | |
| const retained = items.filter((i) => i.stage >= MAX_STAGE); | |
| return { | |
| total: items.length, | |
| dueCount: due.length, | |
| upcomingCount: upcoming.length, | |
| retainedCount: retained.length, | |
| dueItems: due, | |
| upcomingItems: upcoming, | |
| retainedItems: retained, | |
| }; | |
| } | |
| /** | |
| * Record a review result and advance/reset the item's stage. | |
| * Returns the updated item. | |
| */ | |
| export async function recordReview( | |
| userId: number, | |
| topicId: string, | |
| score: number, // 0-1 | |
| now: Date = new Date(), | |
| ) { | |
| const item = await prisma.spacedRepetitionItem.findUnique({ | |
| where: { userId_topicId: { userId, topicId } }, | |
| }); | |
| if (!item) { | |
| throw new Error(`Spaced repetition item not found: ${topicId}`); | |
| } | |
| const newStage = computeNewStage(item.stage, score); | |
| const nextReviewAt = getNextReviewDate(newStage, now); | |
| const passed = score >= PASS_THRESHOLD; | |
| const updated = await prisma.spacedRepetitionItem.update({ | |
| where: { id: item.id }, | |
| data: { | |
| stage: newStage, | |
| lastReviewAt: now, | |
| lastScore: score, | |
| totalReviews: item.totalReviews + 1, | |
| successCount: passed ? item.successCount + 1 : item.successCount, | |
| // If fully retained (nextReviewAt is null), set a far-future date | |
| nextReviewAt: nextReviewAt ?? new Date("2099-12-31T23:59:59Z"), | |
| }, | |
| }); | |
| return { | |
| item: updated, | |
| advanced: newStage > item.stage, | |
| reset: newStage < item.stage, | |
| completed: newStage >= MAX_STAGE, | |
| previousStage: item.stage, | |
| newStage, | |
| }; | |
| } | |