import { sleep } from "./sleep";

/**
 * Retry a function until a condition is met
 *
 * @param fn promise returning function
 * @param condition callback to check if the result meets the condition
 * @param retries max number of retries
 * @param delay delay between retries
 * @returns the result of the promise
 */
export const retry = async <T>(
	fn: () => Promise<T>,
	condition: (res: T) => boolean,
	retries = 5,
	delay = 1000,
): Promise<T | undefined> => {
	if (!retries) return;

	const result = await fn();

	if (condition(result)) {
		return result;
	}

	await sleep(delay);

	return retry(fn, condition, retries - 1, delay);
};
