Skip to content

⚙️ 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

MethodDescription
debounceDelay function execution until a specified time has passed since the last call.
throttleEnsure a function is called at most once in a specified time interval.
onceEnsure a function is only executed once.
retryAutomatically retry an asynchronous function on failure.
parallelProcess array with async callback with controlled parallelism.
delayReturns a promise that resolves after a specified time.
sleepPause execution for a specified duration (alias for delay).

Composition & Logic

MethodDescription
pipeCompose functions from left to right.
composeCompose functions from right to left.
curryTransform a function that takes multiple arguments into a sequence of functions.
memoCache the results of a function based on its arguments.
attemptSafely execute a function and return undefined instead of throwing an error.

Validation & Concurrency

MethodDescription
assertThrow an error if a condition is not met (with advanced options).
assertParamsValidate function parameters against expected types.
workerEasily 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;
});

🔗 All Function Utilities