misc.ts 5.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141
  1. /**
  2. * @module lib/misc
  3. * This module contains miscellaneous functions that don't fit in another category - [see the documentation for more info](https://github.com/Sv443-Network/UserUtils/blob/main/docs.md#misc)
  4. */
  5. import type { ListWithLength, Prettify, Stringifiable } from "./types.js";
  6. /** Which plural form to use when auto-pluralizing */
  7. export type PluralType = "auto" | "-s" | "-ies";
  8. /**
  9. * Automatically appends an `s` to the passed {@linkcode word}, if {@linkcode num} is not equal to 1
  10. * @param word A word in singular form, to auto-convert to plural
  11. * @param num A number, or list-like value that has either a `length`, `count` or `size` property - does not support iterables
  12. * @param pluralType Which plural form to use when auto-pluralizing. Defaults to `auto`, which removes the last char and uses `-ies` for words ending in `y` and simply appends `-s` for all other words
  13. */
  14. export function autoPlural(word: Stringifiable, num: number | ListWithLength, pluralType: PluralType = "auto"): string {
  15. if(typeof num !== "number") {
  16. if(Array.isArray(num) || num instanceof NodeList)
  17. num = num.length;
  18. else if("length" in num)
  19. num = num.length;
  20. else if("count" in num)
  21. num = num.count;
  22. else if("size" in num)
  23. num = num.size;
  24. }
  25. const pType: Exclude<PluralType, "auto"> = pluralType === "auto"
  26. ? String(word).endsWith("y") ? "-ies" : "-s"
  27. : pluralType;
  28. // return `${word}${num === 1 ? "" : "s"}`;
  29. switch(pType) {
  30. case "-s":
  31. return `${word}${num === 1 ? "" : "s"}`;
  32. case "-ies":
  33. return `${String(word).slice(0, -1)}${num === 1 ? "y" : "ies"}`;
  34. default:
  35. return String(word);
  36. }
  37. }
  38. /**
  39. * Inserts the passed values into a string at the respective placeholders.
  40. * The placeholder format is `%n`, where `n` is the 1-indexed argument number.
  41. * @param input The string to insert the values into
  42. * @param values The values to insert, in order, starting at `%1`
  43. */
  44. export function insertValues(input: string, ...values: Stringifiable[]): string {
  45. return input.replace(/%\d/gm, (match) => {
  46. const argIndex = Number(match.substring(1)) - 1;
  47. return (values[argIndex] ?? match)?.toString();
  48. });
  49. }
  50. /** Pauses async execution for the specified time in ms */
  51. export function pauseFor(time: number): Promise<void> {
  52. return new Promise<void>((res) => {
  53. setTimeout(() => res(), time);
  54. });
  55. }
  56. /** Options for the `fetchAdvanced()` function */
  57. export type FetchAdvancedOpts = Prettify<
  58. Partial<{
  59. /** Timeout in milliseconds after which the fetch call will be canceled with an AbortController signal */
  60. timeout: number;
  61. }> & RequestInit
  62. >;
  63. /** Calls the fetch API with special options like a timeout */
  64. export async function fetchAdvanced(input: string | RequestInfo | URL, options: FetchAdvancedOpts = {}): Promise<Response> {
  65. const { timeout = 10000 } = options;
  66. const ctl = new AbortController();
  67. const { signal, ...restOpts } = options;
  68. signal?.addEventListener("abort", () => ctl.abort());
  69. let sigOpts: Partial<RequestInit> = {},
  70. id: ReturnType<typeof setTimeout> | undefined = undefined;
  71. if(timeout >= 0) {
  72. id = setTimeout(() => ctl.abort(), timeout);
  73. sigOpts = { signal: ctl.signal };
  74. }
  75. try {
  76. const res = await fetch(input, {
  77. ...restOpts,
  78. ...sigOpts,
  79. });
  80. typeof id !== "undefined" && clearTimeout(id);
  81. return res;
  82. }
  83. catch(err) {
  84. typeof id !== "undefined" && clearTimeout(id);
  85. throw new Error("Error while calling fetch", { cause: err });
  86. }
  87. }
  88. /**
  89. * 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.
  90. * ValueGen allows for the utmost flexibility when applied to any type, as long as {@linkcode consumeGen()} is used to get the final value.
  91. * @template TValueType The type of the value that the ValueGen should yield
  92. */
  93. export type ValueGen<TValueType> = TValueType | Promise<TValueType> | (() => TValueType | Promise<TValueType>);
  94. /**
  95. * Turns a {@linkcode ValueGen} into its final value.
  96. * @template TValueType The type of the value that the ValueGen should yield
  97. */
  98. export async function consumeGen<TValueType>(valGen: ValueGen<TValueType>): Promise<TValueType> {
  99. return await (typeof valGen === "function"
  100. ? (valGen as (() => Promise<TValueType> | TValueType))()
  101. : valGen
  102. )as TValueType;
  103. }
  104. /**
  105. * 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.
  106. * StringGen allows for the utmost flexibility when dealing with strings, as long as {@linkcode consumeStringGen()} is used to get the final string.
  107. */
  108. export type StringGen = ValueGen<Stringifiable>;
  109. /**
  110. * Turns a {@linkcode StringGen} into its final string value.
  111. * @template TStrUnion The union of strings that the StringGen should yield - this allows for finer type control compared to {@linkcode consumeGen()}
  112. */
  113. export async function consumeStringGen<TStrUnion extends string>(strGen: StringGen): Promise<TStrUnion> {
  114. return (
  115. typeof strGen === "string"
  116. ? strGen
  117. : String(
  118. typeof strGen === "function"
  119. ? await strGen()
  120. : strGen
  121. )
  122. ) as TStrUnion;
  123. }