misc.ts 1.7 KB

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