UNPKG

@kitiumai/utils-ts

Version:

Comprehensive TypeScript utilities for KitiumAI projects

147 lines 3.5 kB
/** * Function utility functions */ /** * Compose functions from right to left */ export function compose(...fns) { return (arg) => fns.reduceRight((result, fn) => fn(result), arg); } /** * Pipe functions from left to right */ export function pipe(...fns) { return (arg) => fns.reduce((result, fn) => fn(result), arg); } /** * Debounce function execution */ export function debounce(fn, delay) { let timeoutId = null; return function (...args) { if (timeoutId) { clearTimeout(timeoutId); } timeoutId = setTimeout(() => { fn.apply(this, args); timeoutId = null; }, delay); }; } /** * Throttle function execution */ export function throttle(fn, interval) { let lastCall = 0; let timeoutId = null; return function (...args) { const now = Date.now(); const timeSinceLastCall = now - lastCall; if (timeSinceLastCall >= interval) { lastCall = now; fn.apply(this, args); } else { if (timeoutId) { clearTimeout(timeoutId); } timeoutId = setTimeout(() => { lastCall = Date.now(); fn.apply(this, args); timeoutId = null; }, interval - timeSinceLastCall); } }; } /** * Memoize function results */ export function memoize(fn, resolver) { const cache = new Map(); return function (...args) { const key = resolver ? resolver(...args) : JSON.stringify(args); if (cache.has(key)) { return cache.get(key); } const result = fn.apply(this, args); cache.set(key, result); return result; }; } /** * Execute function only once */ export function once(fn) { let called = false; let result; return function (...args) { if (!called) { called = true; result = fn.apply(this, args); } return result; }; } /** * Partial application (curry) * Note: Simple implementation for common use cases */ // eslint-disable-next-line @typescript-eslint/no-explicit-any export function curry(fn, arity = fn.length) { // eslint-disable-next-line @typescript-eslint/no-explicit-any return function curried(...args) { if (args.length >= arity) { return fn.apply(this, args); } // eslint-disable-next-line @typescript-eslint/no-explicit-any return (...nextArgs) => curried.apply(this, [...args, ...nextArgs]); }; } /** * Delay function execution */ export function delay(fn, ms) { return (...args) => { return new Promise((resolve) => { setTimeout(() => { resolve(fn(...args)); }, ms); }); }; } /** * Negate function result */ export function negate(fn) { return (...args) => !fn(...args); } /** * Call function with try-catch and return result or error */ export function attempt(fn) { try { return { success: true, value: fn() }; } catch (error) { return { success: false, error: error }; } } /** * Create function that always returns same value */ export function constant(value) { return () => value; } /** * Identity function (returns its argument) */ export function identity(value) { return value; } /** * No-op function (does nothing) */ export function noop() { // Do nothing } //# sourceMappingURL=function.js.map