misc.ts 3.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. /** Represents any value that is either a string itself or can be converted to one (implicitly or explicitly) because it has a toString() method */
  2. export type Stringifiable = string | { toString(): string };
  3. /**
  4. * A type that offers autocomplete for the passed union but also allows any arbitrary value of the same type to be passed.
  5. * Supports unions of strings, numbers and objects.
  6. */
  7. export type LooseUnion<TUnion extends string | number | object> =
  8. (TUnion) | (
  9. TUnion extends string
  10. ? (string & {})
  11. : (
  12. TUnion extends object
  13. ? (object & {})
  14. : (number & {})
  15. )
  16. );
  17. /**
  18. * A type that allows all strings except for empty ones
  19. * @example
  20. * function foo<T extends string>(bar: NonEmptyString<T>) {
  21. * console.log(bar);
  22. * }
  23. */
  24. export type NonEmptyString<TString extends string> = TString extends "" ? never : TString;
  25. /**
  26. * Automatically appends an `s` to the passed {@linkcode word}, if {@linkcode num} is not equal to 1
  27. * @param word A word in singular form, to auto-convert to plural
  28. * @param num If this is an array or NodeList, the amount of items is used
  29. */
  30. export function autoPlural(word: Stringifiable, num: number | unknown[] | NodeList) {
  31. if(Array.isArray(num) || num instanceof NodeList)
  32. num = num.length;
  33. return `${word}${num === 1 ? "" : "s"}`;
  34. }
  35. /** Pauses async execution for the specified time in ms */
  36. export function pauseFor(time: number) {
  37. return new Promise<void>((res) => {
  38. setTimeout(() => res(), time);
  39. });
  40. }
  41. /**
  42. * Calls the passed {@linkcode func} after the specified {@linkcode timeout} in ms (defaults to 300).
  43. * Any subsequent calls to this function will reset the timer and discard all previous calls.
  44. */
  45. export function debounce<TFunc extends (...args: TArgs[]) => void, TArgs = any>(func: TFunc, timeout = 300) { // eslint-disable-line @typescript-eslint/no-explicit-any
  46. let timer: number | undefined;
  47. return function(...args: TArgs[]) {
  48. clearTimeout(timer);
  49. timer = setTimeout(() => func.apply(this, args), timeout) as unknown as number;
  50. };
  51. }
  52. /** Options for the `fetchAdvanced()` function */
  53. export type FetchAdvancedOpts = RequestInit & Partial<{
  54. /** Timeout in milliseconds after which the fetch call will be canceled with an AbortController signal */
  55. timeout: number;
  56. }>;
  57. /** Calls the fetch API with special options like a timeout */
  58. export async function fetchAdvanced(url: string, options: FetchAdvancedOpts = {}) {
  59. const { timeout = 10000 } = options;
  60. const controller = new AbortController();
  61. const id = setTimeout(() => controller.abort(), timeout);
  62. const res = await fetch(url, {
  63. ...options,
  64. signal: controller.signal,
  65. });
  66. clearTimeout(id);
  67. return res;
  68. }
  69. /**
  70. * Inserts the passed values into a string at the respective placeholders.
  71. * The placeholder format is `%n`, where `n` is the 1-indexed argument number.
  72. * @param str The string to insert the values into
  73. * @param values The values to insert, in order, starting at `%1`
  74. */
  75. export function insertValues(str: string, ...values: Stringifiable[]) {
  76. return str.replace(/%\d/gm, (match) => {
  77. const argIndex = Number(match.substring(1)) - 1;
  78. return (values[argIndex] ?? match)?.toString();
  79. });
  80. }