Skip to content

Utility Functions

Comprehensive utility functions demonstrating TypeScript patterns and best practices.

delay()

Delays execution for a specified number of milliseconds.

Signature

typescript
export async function delay(ms: number): Promise<void>

Parameters

  • ms (number): Number of milliseconds to delay

Returns

Promise<void> - Resolves after the specified delay

Usage Examples

typescript
import { delay } from './utils.js';

// Basic usage
await delay(1000); // Wait 1 second

// In async functions
async function processWithDelay() {
  console.log('Starting...');
  await delay(500);
  console.log('Continuing after delay...');
}

// Zero delay (next tick)
await delay(0);

Implementation

Uses setTimeout wrapped in a Promise for clean async/await usage.

safeJsonParse()

Safely parses JSON with comprehensive error handling.

Signature

typescript
export function safeJsonParse(jsonString: string): AsyncResult<unknown>

Parameters

  • jsonString (string): JSON string to parse

Returns

AsyncResult<unknown> - Success or error result object

Usage Examples

typescript
import { safeJsonParse } from './utils.js';

// Parse valid JSON
const result1 = safeJsonParse('{"key": "value"}');
if (result1.success) {
  console.log(result1.data); // { key: "value" }
}

// Handle invalid JSON
const result2 = safeJsonParse('invalid json');
if (!result2.success) {
  console.error(result2.error); // "Unexpected token i in JSON..."
}

// Type-safe usage
function processResult<T>(result: AsyncResult<T>): void {
  if (result.success) {
    // TypeScript knows result.data is type T
    console.log('Success:', result.data);
  } else {
    // TypeScript knows result.error is string
    console.error('Error:', result.error);
  }
}

Error Handling

  • Returns success object with parsed data on valid JSON
  • Returns error object with descriptive message on invalid JSON
  • Never throws exceptions - always returns a result object

formatTimestamp()

Formats a Unix timestamp into a human-readable string.

Signature

typescript
export function formatTimestamp(
  timestamp: number, 
  config: UtilConfig = {}
): string

Parameters

  • timestamp (number): Unix timestamp in milliseconds
  • config (UtilConfig, optional): Configuration options

Returns

string - Formatted date string in "YYYY-MM-DD HH:mm:ss" format

Usage Examples

typescript
import { formatTimestamp } from './utils.js';

// Basic usage
const formatted = formatTimestamp(Date.now());
console.log(formatted); // "2024-01-15 14:30:00"

// With debug logging
const debugFormatted = formatTimestamp(Date.now(), { debug: true });
// Logs: "Formatted timestamp 1705327800000 to 2024-01-15 14:30:00"

// Specific timestamp
const specificTime = new Date('2024-01-15T14:30:00.000Z').getTime();
const result = formatTimestamp(specificTime);
// Returns: "2024-01-15 14:30:00"

Configuration Options

The config parameter accepts a UtilConfig object:

  • debug?: boolean - Enable debug logging
  • maxRetries?: number - Maximum retry attempts (future use)
  • timeout?: number - Timeout in milliseconds (future use)

Type Definitions

UtilConfig

Configuration interface for utility functions.

typescript
export interface UtilConfig {
  /** Enable debug logging */
  debug?: boolean;
  /** Maximum retry attempts */
  maxRetries?: number;
  /** Timeout in milliseconds */
  timeout?: number;
}

AsyncResult<T>

Result type for operations that can succeed or fail.

typescript
export type AsyncResult<T> = {
  success: true;
  data: T;
} | {
  success: false;
  error: string;
};

Usage Pattern

typescript
function processResult<T>(result: AsyncResult<T>): void {
  if (result.success) {
    // TypeScript knows result.data is type T
    console.log('Success:', result.data);
  } else {
    // TypeScript knows result.error is string
    console.error('Error:', result.error);
  }
}

Error Handling Patterns

Promise-Based Errors

typescript
// Functions that can reject
async function riskyOperation(): Promise<string> {
  if (Math.random() > 0.5) {
    throw new Error('Random failure');
  }
  return 'Success';
}

// Proper error handling
try {
  const result = await riskyOperation();
  console.log(result);
} catch (error) {
  console.error('Operation failed:', error.message);
}

Result-Based Errors

typescript
// Functions that return success/error objects
const result = safeJsonParse(jsonString);
if (result.success) {
  // Handle success case
  processData(result.data);
} else {
  // Handle error case
  logError(result.error);
}

Best Practices Demonstrated

Type Safety

  • All functions have explicit return types
  • Interfaces define clear contracts
  • Union types for result handling
  • Generic types for flexibility

Error Handling

  • Multiple error handling patterns
  • Graceful degradation
  • Informative error messages
  • No silent failures

Documentation

  • TSDoc comments for all functions
  • Parameter descriptions and examples
  • Return type documentation
  • Usage examples

Performance

  • Efficient implementations
  • Minimal memory allocation
  • Clean async patterns
  • Proper resource cleanup

Released under the MIT License.