import { RetryStrategy } from './types'; export const pickFirstOption = (name: keyof O, defaultValue: T, ...options: O[]): T => { for (const option of options) { if (typeof option[name] !== 'undefined') { return option[name] as unknown as T; } } return defaultValue; }; export const omit = (data: any, keys: string[]) => { return Object.fromEntries(keys.map((key) => [key, data[key]]).filter(([, value]) => typeof value !== 'undefined')); }; export const sanitize = (data: any) => { return Object.fromEntries(Object.entries(data).filter(([, value]) => typeof value !== 'undefined')) as unknown as T; }; export const defaultRetryStrategy: RetryStrategy = (times: number) => Math.min(times ** 2 * 50, 2000); export const retry = async (fn: () => T | Promise, retryStrategy: RetryStrategy, maxRetries: number): Promise => { let retries = 0; while (true) { try { return (await fn()) as T; } catch (e: any) { const delay = retryStrategy(++retries); await new Promise((resolve, reject) => { if (retries <= maxRetries) { setTimeout(resolve, delay); } else { reject(e); } }); } } }; export const compile = >(pattern: string) => { return Function( 'params', 'return "' + pattern .replace(/\{([^\}]+)}/g, '" + (typeof params.$1 === "undefined" ? "" : encodeURIComponent(params.$1)) + "') .replace(/\[([^\]]+)\]/g, '" + (typeof params.$1 === "undefined" ? "" : params.$1) + "') + '";' ) as (params: T) => string; };