Utilities
This guide documents the utility functions available in acemate. These utilities are categorized by their functionality.
General Utilities
Located in apps/web/src/lib/utils.ts.
cn(...inputs: ClassValue[])
Merges Tailwind CSS classes safely using clsx and tailwind-merge.
formatDate(dateString: string)
Formats a date string to the German locale (dd.mm.yyyy). Returns 'invalid' if the date is invalid.
formatDateTime(dateString: string)
Formats a date string to the German locale with time (dd.mm.yyyy, hh:mm).
truncateTitle(title: string, maxLength: number)
Truncates a string to a specified maximum length, appending "..." if truncated.
getSecondsUntilNextHour()
Calculates the number of seconds remaining until the start of the next hour (plus 10 seconds).
hashStringSHA(str: string)
Asynchronously generates a SHA-256 hash of the input string.
normalizeLatexInMarkdown(text: string)
Normalizes LaTeX delimiters in text to be compatible with Markdown/KaTeX.
-
Escapes dollar signs.
-
Converts
\(...\)to$ ... $. -
Converts
\[...\]to$$ ... $$.
safeDeepClone<T>(obj: T)
Deep clones an object using structuredClone if available, falling back to lodash.clonedeep.
saveAs(url: string, filename: string)
Initiates a file download in the browser given a URL and a filename.
Validation & Security
Password Strength
File: apps/web/src/lib/utils/password-strength.ts
calculatePasswordStrength(password: string): numberReturns a score from 0 to 5 representing the strength of a password based on length, character variety, and patterns.
Referral Validation
File: apps/web/src/lib/utils/referral-validation.ts
validateReferralEligibility(userId: string)Checks if a user is eligible to send a referral based on daily/lifetime limits and cooldown periods.
Filename Sanitization
File: apps/web/src/lib/utils/sanitize-filename.ts
sanitizeFilename(filename: string): stringSanitizes a string for use as a filename, removing control characters, dangerous characters, and whitespaces.
Gamification & Engagement
XP & Levels
File: apps/web/src/lib/utils/gamification.ts
-
calculateLevel(xp: number)Calculates the user's level, progress, and XP requirements for the next level based on total XP. -
formatXP(xp: number)Formats XP numbers (e.g., 1200 becomes "1.2K").
Streaks
File: apps/web/src/lib/utils/streak.ts
calculateStreak(streakData: { date: string }[])Calculates the current streak count from an array of date objects.
Infrastructure & Marketing
Marketing Tracking
File: apps/web/src/lib/utils/track-signup.ts
trackSignupEvent(email: string, userId: string)Tracks user signup events across multiple platforms (TikTok, Meta, Google) and sends server-side events.
Storage (R2)
File: apps/web/src/lib/r2.ts
generateSignedUrl(key: string)Generates a signed URL for accessing files in Cloudflare R2 storage. In development, it returns a base64 encoded data URL.
Content Processing
Markdown
File: apps/web/src/lib/markdown.ts
cleanMarkdown(content: string)Cleans and normalizes markdown content, handling HTML entities, legacy citations, and LaTeX math delimiters.
Shuffle
File: apps/web/src/lib/shuffle.ts
shuffle<T>(arr: T[], seedStr: string): T[]Performs a deterministic shuffle of an array using a seeded pseudo-random number generator (Fisher-Yates algorithm).
React Helpers
Merge Refs
File: apps/web/src/lib/utils/merge-refs.ts
mergeRefs<T>(refs: Array<...>): React.RefCallback<T>Merges multiple React refs (mutable or callback) into a single callback.
Sorting
Natural Compare
File: apps/web/src/lib/utils/natural-compare.ts
naturalCompare(a: string, b: string)Performs a locale-aware string comparison that treats digit sequences numerically (e.g., "Item 2" comes before "Item 10").
Shared Package Utilities
Utilities available in @packages/utils (used across apps and services).
Data & Types
chunkArray<T>(array: T[], size: number)
File: packages/utils/src/chunk-array.ts
Splits an array into smaller chunks of a specific size.
groupBy<T>(array: T[], by: By<T>)
File: packages/utils/src/group-by.ts
Groups an array of objects by a specific key or function.
Either Pattern
File: packages/utils/src/either.ts
Functional error handling pattern with Left (error) and Right (success) types.
left(value),right(value)isLeft(either),isRight(either)
Try-Catch Wrapper
File: packages/utils/src/try-catch.ts
tryCatch(fn): Executes synchronous or asynchronous functions and returns a tuple [result, error]. Eliminates the need for try-catch blocks in business logic.
tryCatch.sync(fn)tryCatch.async(fn)tryCatchToEither(result): Converts the tuple result to anEithertype.
Invariant
File: packages/utils/src/invariant.ts
invariant(condition, message): Asserts that a condition is true, otherwise throws an error with the provided message. Useful for checking assumptions.
Content & Conversion
Tiptap & Markdown Conversion
Files: packages/utils/src/convert/
markdownToTiptap(markdown: string): Converts Markdown string to Tiptap JSON structure, handling custom extensions like math blocks and citations.tiptapToMarkdown(content: JSON | string): Converts Tiptap JSON content back to Markdown using a custom serializer.
Citations
File: packages/utils/src/citations.ts
Regex patterns and helpers for parsing and constructing citations (e.g., [[citation:itemId:pageNum]]).
- Regex constants:
CITATION_REGEX,INDIVIDUAL_CITATION_REGEX, etc. - Helpers:
constructCitation,convertToIndividualCitation.
Performance & Analytics
Exam Performance
File: packages/utils/src/performance/exam/calculate-performance.ts
calculatePerformance(results, ...): Calculates a performance score (0-100) based on a list of exam results using an exponential moving average with velocity to emphasize recent progress.
Infrastructure
Logger
File: packages/utils/src/logger.ts
Simple wrapper around console for consistent logging in workers and workflows.
Language Helpers
File: packages/utils/src/language-id-to-name.ts
languageIdToName(languageId): Converts internal language IDs to display names.
Formatting
Bytes Formatter
File: packages/utils/src/formatters.ts
formatBytes(bytes: number): Formats a number of bytes into a human-readable string (e.g., "10.5 MB").