Version 1.0 squash

This commit is contained in:
Kenan Alić
2025-10-21 18:45:02 +02:00
parent 4d52f14287
commit 4321a45042
30 changed files with 2534 additions and 15 deletions

65
web/src/lib/result.ts Normal file
View File

@@ -0,0 +1,65 @@
/**
* Result Utility
*
* Go-style error handling utilities for safer, more explicit error handling.
* Provides Result type and tryCatch wrappers to eliminate try-catch boilerplate.
*/
/**
* Go-style Result type for explicit error handling
* Returns [data, null] on success or [null, error] on failure
*
* @example
* const [data, error] = tryCatch(() => riskyOperation());
* if (error) {
* // Handle error
* return;
* }
* // Use data safely
*/
export type Result<T, E = Error> = [T, null] | [null, E];
/**
* Wraps a function in try-catch and returns Result tuple
* Similar to Go's (value, error) pattern
*
* @param fn Function to execute
* @returns Tuple of [result, null] or [null, error]
*/
export function tryCatch<T>(fn: () => T): Result<T> {
try {
const result = fn();
return [result, null];
} catch (error) {
return [null, error instanceof Error ? error : new Error(String(error))];
}
}
/**
* Async version of tryCatch for promises
*
* @param fn Async function to execute
* @returns Promise resolving to tuple of [result, null] or [null, error]
*/
export async function tryCatchAsync<T>(fn: () => Promise<T>): Promise<Result<T>> {
try {
const result = await fn();
return [result, null];
} catch (error) {
return [null, error instanceof Error ? error : new Error(String(error))];
}
}
/**
* Safely executes a void function, ignoring any errors
* Perfect for cleanup operations like unsubscribe where errors don't matter
*
* @param fn Function to execute safely
*/
export function safely(fn: () => void): void {
try {
fn();
} catch {
/* Ignore errors during cleanup */
}
}