misc.ts 5.5 KB

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