misc.ts 4.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109
  1. import type { Prettify, Stringifiable } from "./types.js";
  2. /**
  3. * Automatically appends an `s` to the passed {@linkcode word}, if {@linkcode num} is not equal to 1
  4. * @param word A word in singular form, to auto-convert to plural
  5. * @param num If this is an array or NodeList, the amount of items is used
  6. */
  7. export function autoPlural(word: Stringifiable, num: number | unknown[] | NodeList): string {
  8. if(Array.isArray(num) || num instanceof NodeList)
  9. num = num.length;
  10. return `${word}${num === 1 ? "" : "s"}`;
  11. }
  12. /**
  13. * Inserts the passed values into a string at the respective placeholders.
  14. * The placeholder format is `%n`, where `n` is the 1-indexed argument number.
  15. * @param input The string to insert the values into
  16. * @param values The values to insert, in order, starting at `%1`
  17. */
  18. export function insertValues(input: string, ...values: Stringifiable[]): string {
  19. return input.replace(/%\d/gm, (match) => {
  20. const argIndex = Number(match.substring(1)) - 1;
  21. return (values[argIndex] ?? match)?.toString();
  22. });
  23. }
  24. /** Pauses async execution for the specified time in ms */
  25. export function pauseFor(time: number): Promise<void> {
  26. return new Promise<void>((res) => {
  27. setTimeout(() => res(), time);
  28. });
  29. }
  30. /** Options for the `fetchAdvanced()` function */
  31. export type FetchAdvancedOpts = Prettify<
  32. Partial<{
  33. /** Timeout in milliseconds after which the fetch call will be canceled with an AbortController signal */
  34. timeout: number;
  35. }> & RequestInit
  36. >;
  37. /** Calls the fetch API with special options like a timeout */
  38. export async function fetchAdvanced(input: string | RequestInfo | URL, options: FetchAdvancedOpts = {}): Promise<Response> {
  39. const { timeout = 10000 } = options;
  40. const { signal, abort } = new AbortController();
  41. options.signal?.addEventListener("abort", abort);
  42. let signalOpts: Partial<RequestInit> = {},
  43. id: ReturnType<typeof setTimeout> | undefined = undefined;
  44. if(timeout >= 0) {
  45. id = setTimeout(() => abort(), timeout);
  46. signalOpts = { signal };
  47. }
  48. try {
  49. const res = await fetch(input, {
  50. ...options,
  51. ...signalOpts,
  52. });
  53. id && clearTimeout(id);
  54. return res;
  55. }
  56. catch(err) {
  57. id && clearTimeout(id);
  58. throw err;
  59. }
  60. }
  61. /**
  62. * A ValueGen value is either its type, a promise that resolves to its type, or a function that returns its type, either synchronous or asynchronous.
  63. * ValueGen allows for the utmost flexibility when applied to any type, as long as {@linkcode consumeGen()} is used to get the final value.
  64. * @template TValueType The type of the value that the ValueGen should yield
  65. */
  66. export type ValueGen<TValueType> = TValueType | Promise<TValueType> | (() => TValueType | Promise<TValueType>);
  67. /**
  68. * Turns a {@linkcode ValueGen} into its final value.
  69. * @template TValueType The type of the value that the ValueGen should yield
  70. */
  71. export async function consumeGen<TValueType>(valGen: ValueGen<TValueType>): Promise<TValueType> {
  72. return await (typeof valGen === "function"
  73. ? (valGen as (() => Promise<TValueType> | TValueType))()
  74. : valGen
  75. )as TValueType;
  76. }
  77. /**
  78. * A StringGen value is either a string, anything that can be converted to a string, or a function that returns one of the previous two, either synchronous or asynchronous, or a promise that returns a string.
  79. * StringGen allows for the utmost flexibility when dealing with strings, as long as {@linkcode consumeStringGen()} is used to get the final string.
  80. */
  81. export type StringGen = ValueGen<Stringifiable>;
  82. /**
  83. * Turns a {@linkcode StringGen} into its final string value.
  84. * @template TStrUnion The union of strings that the StringGen should yield - this allows for finer type control compared to {@linkcode consumeGen()}
  85. */
  86. export async function consumeStringGen<TStrUnion extends string>(strGen: StringGen): Promise<TStrUnion> {
  87. return (
  88. typeof strGen === "string"
  89. ? strGen
  90. : String(
  91. typeof strGen === "function"
  92. ? await strGen()
  93. : strGen
  94. )
  95. ) as TStrUnion;
  96. }