UNPKG

@catbee/utils

Version:

A modular, production-grade utility toolkit for Node.js and TypeScript, designed for robust, scalable applications (including Express-based services). All utilities are tree-shakable and can be imported independently.

163 lines (160 loc) 5.23 kB
/* * The MIT License * * Copyright (c) 2026 Catbee Technologies. https://catbee.in/license * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ /** * Options for timing function execution. */ interface TimingOptions { /** Optional label for the timing (defaults to function name) */ label?: string; /** Whether to log the timing (default: false) */ log?: boolean; /** Log level to use if logging is enabled (default: 'debug') */ logLevel?: 'trace' | 'debug' | 'info' | 'warn' | 'error'; } /** * Result of a timing operation. */ interface TimingResult { /** Duration in milliseconds */ durationMs: number; /** Duration in seconds */ durationSec: number; /** Start timestamp */ startTime: number; /** End timestamp */ endTime: number; /** Label used for the timing */ label: string; } /** * Measure the execution time of a synchronous function. * * @param fn - Function to measure * @param options - Timing options * @returns Result containing the return value and timing information * * @example * ```typescript * const { result, timing } = timeSync(() => { * // Some expensive operation * return computeResult(); * }, { label: 'Computation', log: true }); * * console.log(`Result: ${result}, took ${timing.durationMs}ms`); * ``` */ declare function timeSync<T>(fn: () => T, options?: TimingOptions): { result: T; timing: TimingResult; }; /** * Measure the execution time of an asynchronous function. * * @param fn - Async function to measure * @param options - Timing options * @returns Promise resolving to result and timing information * * @example * ```typescript * const { result, timing } = await timeAsync(async () => { * // Some expensive async operation * const data = await fetchData(); * return processData(data); * }, { label: 'API Request', log: true }); * * console.log(`Fetched ${result.length} items in ${timing.durationSec.toFixed(2)}s`); * ``` */ declare function timeAsync<T>(fn: () => Promise<T>, options?: TimingOptions): Promise<{ result: T; timing: TimingResult; }>; /** * Create a timing decorator for class methods. * * @param options - Timing options * @returns Method decorator * * @example * ```typescript * class DataService { * @timed({ log: true, logLevel: 'info' }) * async fetchData() { * // ...implementation * } * } * ``` */ declare function timed(options?: TimingOptions): (target: any, propertyKeyOrContext: string | symbol | any, descriptor?: PropertyDescriptor) => void; /** * Memoize function results with optional TTL and max cache size. * * @param fn - Function to memoize * @param options - Memoization options * @returns Memoized function * * @example * ```typescript * // Cache results for 30 seconds, with a maximum of 100 entries * const cachedFetch = memoize( * async (url) => { * const response = await fetch(url); * return response.json(); * }, * { ttl: 30000, maxSize: 100, cacheKey: (url) => url } * ); * ``` */ declare function memoize<T, Args extends any[]>(fn: (...args: Args) => T, options?: { /** Time-to-live in milliseconds (default: indefinite) */ ttl?: number; /** Maximum cache size (default: unlimited) */ maxSize?: number; /** Function to generate a cache key from arguments */ cacheKey?: (...args: Args) => string; /** Auto-cleanup interval in milliseconds (default: disabled) */ autoCleanupMs?: number; }): (...args: Args) => T; /** * Track memory usage for a function execution. * * @param fn - Function to track * @param options - Memory tracking options * @returns Result and memory usage information */ declare function trackMemoryUsage<T>(fn: () => T, options?: { /** Whether to log the memory usage (default: false) */ log?: boolean; /** Label for the memory tracking (default: function name) */ label?: string; }): { result: T; memoryUsage: { before: NodeJS.MemoryUsage; after: NodeJS.MemoryUsage; diff: Record<string, number>; }; }; export { memoize, timeAsync, timeSync, timed, trackMemoryUsage }; export type { TimingOptions, TimingResult };