misc.ts 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. /** Options for the `fetchAdvanced()` function */
  2. export type FetchAdvancedOpts = RequestInit & Partial<{
  3. /** Timeout in milliseconds after which the fetch call will be canceled with an AbortController signal */
  4. timeout: number;
  5. }>;
  6. /**
  7. * Automatically appends an `s` to the passed `word`, if `num` is not equal to 1
  8. * @param word A word in singular form, to auto-convert to plural
  9. * @param num If this is an array or NodeList, the amount of items is used
  10. */
  11. export function autoPlural(word: string, num: number | unknown[] | NodeList) {
  12. if(Array.isArray(num) || num instanceof NodeList)
  13. num = num.length;
  14. return `${word}${num === 1 ? "" : "s"}`;
  15. }
  16. /** Pauses async execution for the specified time in ms */
  17. export function pauseFor(time: number) {
  18. return new Promise<void>((res) => {
  19. setTimeout(() => res(), time);
  20. });
  21. }
  22. /**
  23. * Calls the passed `func` after the specified `timeout` in ms.
  24. * Any subsequent calls to this function will reset the timer and discard previous calls.
  25. */
  26. export function debounce<TFunc extends (...args: TArgs[]) => void, TArgs = any>(func: TFunc, timeout = 300) { // eslint-disable-line @typescript-eslint/no-explicit-any
  27. let timer: number | undefined;
  28. return function(...args: TArgs[]) {
  29. clearTimeout(timer);
  30. timer = setTimeout(() => func.apply(this, args), timeout) as unknown as number;
  31. };
  32. }
  33. /** Calls the fetch API with special options like a timeout */
  34. export async function fetchAdvanced(url: string, options: FetchAdvancedOpts = {}) {
  35. const { timeout = 10000 } = options;
  36. const controller = new AbortController();
  37. const id = setTimeout(() => controller.abort(), timeout);
  38. const res = await fetch(url, {
  39. ...options,
  40. signal: controller.signal,
  41. });
  42. clearTimeout(id);
  43. return res;
  44. }