⚙️ Function Utilities
Function utilities provide a powerful set of tools to control execution, compose logic, and enhance function behavior in a type-safe way. Use these helpers for debouncing, throttling, memoization, retries, and more.
📚 Quick Reference
Execution Control
| Method | Description |
|---|---|
debounce | Delay function execution until a specified time has passed since the last call. |
throttle | Ensure a function is called at most once in a specified time interval. |
once | Ensure a function is only executed once. |
retry | Automatically retry an asynchronous function on failure. |
parallel | Process array with async callback with controlled parallelism. |
delay | Returns a promise that resolves after a specified time. |
sleep | Pause execution for a specified duration (alias for delay). |
Composition & Logic
| Method | Description |
|---|---|
pipe | Compose functions from left to right. |
compose | Compose functions from right to left. |
curry | Transform a function that takes multiple arguments into a sequence of functions. |
memo | Cache the results of a function based on its arguments. |
attempt | Safely execute a function and return undefined instead of throwing an error. |
Validation & Concurrency
| Method | Description |
|---|---|
assert | Throw an error if a condition is not met (with advanced options). |
assertParams | Validate function parameters against expected types. |
worker | Easily run heavy functions in a Web Worker. |
💡 Practical Examples
Controlling Execution
ts
import { debounce, throttle, retry } from '@vielzeug/toolkit';
// Handle window resize (debounce)
const handleResize = debounce(() => {
console.log('Resize handled');
}, 250);
// Handle scroll (throttle)
const handleScroll = throttle(() => {
console.log('Scroll handled');
}, 100);
// Robust API calls
const data = await retry(
async () => {
return fetch('/api/data').then((res) => res.json());
},
{ retries: 3, delay: 1000 },
);Functional Composition
ts
import { pipe, memo } from '@vielzeug/toolkit';
const add = (n: number) => n + 1;
const double = (n: number) => n * 2;
// Compose functions
const addAndDouble = pipe(add, double);
addAndDouble(2); // (2 + 1) * 2 = 6
// Memoize heavy calculations
const heavyCalc = memo((n: number) => {
// complex logic...
return n * n;
});