blend / promise-utils

Lodash-like, dependency-free utilities for native ES6 promises.
MIT License
282 stars 15 forks source link

`defer` function inspired by `useDeferredValue` hook in React #85

Open raviqqe opened 1 year ago

raviqqe commented 1 year ago

Description

This is a feature request for a defer function that returns a value of the last invocation of a function. It's similar to caching/throttling/debouncing but I couldn't find any equivalent in this library or in Lodash. So I'm proposing this to see if any other people have similar use cases.

export const defer = <T, F extends (...args: never[]) => Promise<T>>(
  callback: F
): ((...args: Parameters<F>) => Promise<T>) => {
  let cache: Promise<T> | undefined = undefined;

  return async (...args: Parameters<F>): Promise<T> => {
    const lastCache = cache;
    cache = callback(args);

    return lastCache ?? cache;
  };
};

it("defers a value", async () => {
  const callback = defer(async (x: number) => x);

  expect(await callback(1)).toBe(1);
  expect(await callback(2)).toBe(1);
  expect(await callback(3)).toBe(2);
  expect(await callback(4)).toBe(3);
});

References