Useful utility functions
-
Invariant
Checks if a condition is met, otherwise throws.
const INVARIANT_PREFIX = "Invariant failed"; export function invariant( condition: unknown, // Can provide a function for cases where the message takes some effort to compute message?: string | (() => string), ): asserts condition { if (condition) { return; } // In production -> we strip the message, but still throw if (isProduction) { throw new Error(INVARIANT_PREFIX); } // Not in production -> we allow the message to pass through and throw const providedMessage = typeof message === "function" ? message() : message; throw new Error( providedMessage ? `${INVARIANT_PREFIX}: ${providedMessage}` : INVARIANT_PREFIX, ); } -
Sleep
Stalls execution for a specified duration in milliseconds.
export async function sleep(ms: number) { return new Promise((resolve) => { setTimeout(resolve, ms); }); } -
Safe Try (sync)
Replaces a try-catch block containing synchronous code, returning
[error, result]instead.export function safeTry<T, E = Error>(operation: T): [T, null] | [null, E] { try { const result = operation; return [result, null]; } catch (e: unknown) { return [null, e as E]; } } -
Safe Try (sync)
Replace a try-catch block containing asynchronous code, returning
Promise<[error, result]>instead.export function safeTry<T, E = Error>(operation: T): [T, null] | [null, E] { try { const result = operation; return [result, null]; } catch (e: unknown) { return [null, e as E]; } } -
Quick Array
Generates an array of a specified length. If a value is provided, the array will be filled with that value; otherwise, it will contain consecutive numbers starting from 1.
export function quickArray(length: number, fillValue?: any) { return Array.from({ length }, (_, i) => fillValue || i + 1); } -
Get Element and Index from Array
Searches through an array and returns the first element that satisfies the given predicate, along with its index. If no match is found, it returns
[null, -1].export function findElement<T>( array: T[], predicate: (item: T) => boolean ): [T, number] | [null, -1] { for (let i = 0; i < array.length; i++) { if (predicate(array[i])) { return [array[i], i]; } } return [null, -1]; }; -
Compute File Checksum
Computes the checksum of a file using SHA-256.
export async function computeSHA256 = async (file: File) { const arrayBuffer = await file.arrayBuffer(); const hashBuffer = await crypto.subtle.digest("SHA-256", arrayBuffer); const hashArray = Array.from(new Uint8Array(hashBuffer)); const hashHex = hashArray .map((byte) => byte.toString(16).padStart(2, "0")) .join(""); return hashHex; }; -
Generate Strong Name
Generate a cryptographically strong name using random values.
export function generateStrongName(bytes = 32) { const array = new Uint8Array(bytes); crypto.getRandomValues(array); return [...array] .map((byte) => byte.toString(16).padStart(2, "0")) .join(""); }; -
Slugify
Transforms a string into a 'slug'.
export function slugify(text: string) { return text .toString() .toLowerCase() .trim() .replace(/\s+/g, "-") .replace(/&/g, "-and-") .replace(/[^\w-]+/g, "") .replace(/--+/g, "-"); } -
String to camelCase
Transforms a string into a camelCase string.
export function toCamelCase = (slug: string) { const regex = /^[a-z-]+$/; if (!regex.test(slug)) { throw new Error("Invalid slug"); } return slug .split("-") .map((word, index) => index ? word.charAt(0).toUpperCase() + word.slice(1) : word ) .join(""); }; -
Slug To TitleCase
Transforms a slug string into a title case string.
export function slugToTitle(slug: string) { const exceptions = [ "the", "and", "or", "but", "nor", "a", "an", "so", "for", "yet", "at", "by", "from", "of", "on", "to", "with", "in", "up", "over", "as", ]; const words = slug.split("-"); return words .map((word, index) => { if ( index === 0 || index === words.length - 1 || !exceptions.includes(word) ) { return word.charAt(0).toUpperCase() + word.slice(1); } else { return word; } }) .join(" "); };