misc.ts 1.8 KB

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