-
Notifications
You must be signed in to change notification settings - Fork 13
Open
Description
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
Labels
No labels