From 993a9883a17d301d94fcdc77fa55a8e2a6295326 Mon Sep 17 00:00:00 2001 From: QuantCode Agent Date: Tue, 18 Aug 2026 16:21:03 +0000 Subject: [PATCH] fix: repair failing tests across utility modules - calculator: divide now throws on zero divisor instead of returning Infinity - string-utils: implement truncate (word-boundary, ellipsis budget, edge guards); wordCount splits on whitespace runs - task-manager: implement remove/update partial semantics and sortBy with stable tiebreak - date-utils: formatRelative rounds day magnitude symmetrically (fixes 36h boundary) - validator: isEmail accepts multi-level subdomains and 2+ char TLDs; isUrl no longer rejects URLs with a port --- src/calculator.ts | 2 +- src/date-utils.ts | 9 +++++---- src/string-utils.ts | 27 +++++++++++++++++++++------ src/task-manager.ts | 43 +++++++++++++++++++++++++++++++++++-------- src/validator.ts | 19 +++++++++---------- 5 files changed, 71 insertions(+), 29 deletions(-) diff --git a/src/calculator.ts b/src/calculator.ts index 68b894d..8fa3de6 100644 --- a/src/calculator.ts +++ b/src/calculator.ts @@ -15,7 +15,7 @@ export function multiply(a: number, b: number): number { return a * b } -// BUG: Division by zero is not handled export function divide(a: number, b: number): number { + if (b === 0) throw new Error("Division by zero") return a / b } diff --git a/src/date-utils.ts b/src/date-utils.ts index 37272a7..c5d862e 100644 --- a/src/date-utils.ts +++ b/src/date-utils.ts @@ -6,15 +6,16 @@ * Format a date as a human-readable relative string. * e.g. "2 days ago", "just now", "in 3 hours" * - * BUG: off-by-one — uses Math.floor where Math.round is needed for days, - * causing "1 day ago" to appear for anything from 12h to 47h. + * Day counts are rounded to the nearest day on the magnitude of the + * difference, so past and future read symmetrically: 36 hours ago is + * "2 days ago" and 36 hours ahead is "in 2 days". */ export function formatRelative(date: Date, now: Date = new Date()): string { const diffMs = now.getTime() - date.getTime() const diffSec = diffMs / 1000 const diffMin = diffSec / 60 const diffHours = diffMin / 60 - const diffDays = Math.floor(diffHours / 24) // BUG: should be Math.round + const diffDays = Math.round(Math.abs(diffHours) / 24) if (Math.abs(diffSec) < 60) return "just now" if (Math.abs(diffMin) < 60) { @@ -25,7 +26,7 @@ export function formatRelative(date: Date, now: Date = new Date()): string { const h = Math.round(Math.abs(diffHours)) return diffMs > 0 ? `${h} hour${h !== 1 ? "s" : ""} ago` : `in ${h} hour${h !== 1 ? "s" : ""}` } - const d = Math.abs(diffDays) + const d = diffDays return diffMs > 0 ? `${d} day${d !== 1 ? "s" : ""} ago` : `in ${d} day${d !== 1 ? "s" : ""}` } diff --git a/src/string-utils.ts b/src/string-utils.ts index 63fba18..dc420e9 100644 --- a/src/string-utils.ts +++ b/src/string-utils.ts @@ -11,10 +11,25 @@ export function reverse(str: string): string { return str.split("").reverse().join("") } -// TODO: implement truncate — should truncate at a word boundary, with "..." -// counting toward maxLength. Return unchanged if str.length <= maxLength. +const ELLIPSIS = "..." + +/** + * Truncate a string to at most maxLength characters, cutting at a word + * boundary where possible. The ellipsis counts toward maxLength, so the + * returned string is never longer than maxLength. + * Returns the string unchanged when it already fits, and "" when maxLength + * is non-finite or not positive (no output can satisfy the invariant). + */ export function truncate(str: string, maxLength: number): string { - throw new Error("not implemented") + if (!Number.isFinite(maxLength) || maxLength <= 0) return "" + if (str.length <= maxLength) return str + if (maxLength <= ELLIPSIS.length) return str.slice(0, maxLength) + + const budget = maxLength - ELLIPSIS.length + const head = str.slice(0, budget) + const lastSpace = head.lastIndexOf(" ") + const cut = lastSpace > 0 ? head.slice(0, lastSpace) : head + return cut.trimEnd() + ELLIPSIS } export function slugify(str: string): string { @@ -24,8 +39,8 @@ export function slugify(str: string): string { .replace(/^-|-$/g, "") } -// BUG: This doesn't handle multiple consecutive spaces export function wordCount(str: string): number { - if (!str.trim()) return 0 - return str.split(" ").length + const trimmed = str.trim() + if (!trimmed) return 0 + return trimmed.split(/\s+/).length } diff --git a/src/task-manager.ts b/src/task-manager.ts index a920e85..1b929bb 100644 --- a/src/task-manager.ts +++ b/src/task-manager.ts @@ -52,20 +52,47 @@ export class TaskManager { return true } - // TODO: implement — remove a task by id, return true if removed, false if not found + /** + * Remove a task by id. Returns true if a task was removed, false if not found. + */ remove(id: string): boolean { - throw new Error("not implemented") + return this.tasks.delete(id) } - // TODO: implement — update title/description/priority of a task - // return true if updated, false if not found + /** + * Update the title, description and/or priority of a task. + * Returns true if the task was found and updated, false if not found. + * Only keys explicitly present in `changes` are applied. + */ update(id: string, changes: Partial>): boolean { - throw new Error("not implemented") + const task = this.tasks.get(id) + if (!task) return false + if ("title" in changes && changes.title !== undefined) task.title = changes.title + if ("description" in changes) task.description = changes.description + if ("priority" in changes && changes.priority !== undefined) task.priority = changes.priority + return true } - // TODO: implement — return all tasks sorted by the given field - // priority sort order: high > medium > low + /** + * Return all tasks sorted by the given field. + * priority: high > medium > low. status: pending > in_progress > completed. + * createdAt: oldest first. Ties fall back to insertion order (id). + */ sortBy(field: "priority" | "createdAt" | "status"): Task[] { - throw new Error("not implemented") + const priorityRank: Record = { high: 0, medium: 1, low: 2 } + const statusRank: Record = { pending: 0, in_progress: 1, completed: 2 } + + const byId = (a: Task, b: Task) => Number(a.id) - Number(b.id) + + return Array.from(this.tasks.values()).sort((a, b) => { + switch (field) { + case "priority": + return priorityRank[a.priority] - priorityRank[b.priority] || byId(a, b) + case "status": + return statusRank[a.status] - statusRank[b.status] || byId(a, b) + case "createdAt": + return a.createdAt.getTime() - b.createdAt.getTime() || byId(a, b) + } + }) } } diff --git a/src/validator.ts b/src/validator.ts index 27bf385..0ee704d 100644 --- a/src/validator.ts +++ b/src/validator.ts @@ -2,27 +2,26 @@ * Input validation utilities. */ +const EMAIL_LABEL = "[a-zA-Z0-9](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?" +const EMAIL_RE = new RegExp(`^[^\\s@]+@${EMAIL_LABEL}(?:\\.${EMAIL_LABEL})*\\.[a-zA-Z]{2,}$`) + /** * Returns true if the string is a valid email address. - * - * BUG: the regex does not allow subdomains (e.g. user@mail.example.com fails) - * and rejects valid TLDs longer than 4 chars (e.g. .museum, .travel). + * Supports subdomains (user@mail.example.com) and TLDs of any length + * of two or more characters (.com, .museum, .travel). */ export function isEmail(value: string): boolean { - // BUG: too restrictive — missing subdomain support and long TLDs - return /^[^\s@]+@[^\s@]+\.[a-zA-Z]{2,4}$/.test(value) + return EMAIL_RE.test(value) } /** - * Returns true if the string is a valid URL (http or https). - * - * BUG: rejects URLs with ports (e.g. http://localhost:3000) + * Returns true if the string is a valid http or https URL. + * An explicit port is permitted (e.g. http://localhost:3000). */ export function isUrl(value: string): boolean { try { const url = new URL(value) - // BUG: only allows http/https but also rejects valid port usage - return (url.protocol === "http:" || url.protocol === "https:") && url.port === "" + return url.protocol === "http:" || url.protocol === "https:" } catch { return false }