UNPKG

@ukbhra/common-utils

Version:

A collection of reusable utility functions for string, object, validation, and general operations in Node.js projects.

54 lines 1.59 kB
import crypto from 'crypto'; export const sleep = (ms) => new Promise(resolve => setTimeout(resolve, ms)); export const retry = async (fn, retries = 3, delayMs = 1000) => { try { return await fn(); } catch (err) { if (retries === 0) throw err; await sleep(delayMs); return retry(fn, retries - 1, delayMs); } }; export const generateUUID = () => crypto.randomUUID(); // Node 14.17+ and modern browsers export const clamp = (num, min, max) => Math.min(Math.max(num, min), max); export const noop = () => { }; export const range = (start, end, step = 1) => { const arr = []; for (let i = start; i < end; i += step) { arr.push(i); } return arr; }; export const randomInt = (min, max) => Math.floor(Math.random() * (max - min + 1)) + min; export const once = (fn) => { let called = false; let result; return ((...args) => { if (!called) { called = true; result = fn(...args); } return result; }); }; export const debounce = (fn, wait) => { let timeout; return ((...args) => { clearTimeout(timeout); timeout = setTimeout(() => fn(...args), wait); }); }; export const throttle = (fn, limit) => { let inThrottle; return ((...args) => { if (!inThrottle) { fn(...args); inThrottle = true; setTimeout(() => (inThrottle = false), limit); } }); }; /* Removed custom setTimeout to avoid conflict with global setTimeout */ //# sourceMappingURL=generalUtil.js.map