Skip to content

defer function inspired by useDeferredValue hook in React #85

@raviqqe

Description

@raviqqe

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions