DEV Community

Five simple utils that always come in handy in your JavaScript project

Wait

The wait utility is primarily used to introduce a delay in your asynchronous code execution. This can be beneficial for scenarios like simulating network latency or creating timed animations.

const wait = (timeout) => 
  new Promise(resolve => setTimeout(resolve, timeout));
Enter fullscreen mode Exit fullscreen mode

Debounce

Debounce is a powerful technique for optimizing performance in event-driven applications. It ensures that a function is executed only after a certain amount of time has elapsed since the last call, even if the event fires repeatedly. This is particularly useful for events like resizing a window or user input in search bars to prevent excessive function calls.

const debounce = (func, timeout) => {
  let timeoutID;
  return function (this, ...args) {
     clearTimeout(timeoutID);
     timeoutID = setTimeout(() => func.apply(this, args), timeout);
  };
};
Enter fullscreen mode Exit fullscreen mode

Throttle

Similar to debounce, throttle limits the execution frequency of a function. However, unlike debounce which guarantees execution at most once within the timeout period, throttle allows the function to be called as long as the timeout window hasn't passed since the last execution. This is useful for scenarios like handling rapid mouse movements or API calls that should be rate-limited.

const throttle = (func, timeout) => {
  let timeoutID = null;
  return function (this, ...args) {
    if(!timeoutID) {
      func.apply(this, args);
      timeoutID = setTimeout(() => {
        timeoutID = null;
      }, timeout)
    } 
  }
}
Enter fullscreen mode Exit fullscreen mode

Memo

Memo is an optimization function that stores the results of passed function calls based on their arguments. Subsequent calls with the same arguments retrieve the cached value instead of re-executing the function. This can significantly improve performance for expensive calculations.

const memo = (func) => {
  const cache = new Map();
  return (...args) => {
    const key = args.join("");

    if(cache.has(key)) return cache.get(key);

    const value = func(...args);
    cache.set(key, value);
    return value;
  };
};
Enter fullscreen mode Exit fullscreen mode

Curry

Currying is a transformation that converts a function with multiple arguments into a sequence of functions with single arguments. This allows you to partially apply arguments and create new functions with a pre-defined set of arguments.

const curry = (func) => {
  return function curried(...args) {
    if (args.length >= func.length) {
      return func.apply(this, args);
    } else {
      return function(...args2) {
        return curried.apply(this, args.concat(args2));
      }
    }
  };
}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)