1
0

misc.ts 6.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131
  1. import { getUnsafeWindow } from "./dom";
  2. import type { Stringifiable } from "./types";
  3. /**
  4. * Automatically appends an `s` to the passed {@linkcode word}, if {@linkcode num} is not equal to 1
  5. * @param word A word in singular form, to auto-convert to plural
  6. * @param num If this is an array or NodeList, the amount of items is used
  7. */
  8. export function autoPlural(word: Stringifiable, num: number | unknown[] | NodeList) {
  9. if(Array.isArray(num) || num instanceof NodeList)
  10. num = num.length;
  11. return `${word}${num === 1 ? "" : "s"}`;
  12. }
  13. /** Pauses async execution for the specified time in ms */
  14. export function pauseFor(time: number) {
  15. return new Promise<void>((res) => {
  16. setTimeout(() => res(), time);
  17. });
  18. }
  19. /**
  20. * Calls the passed {@linkcode func} after the specified {@linkcode timeout} in ms (defaults to 300).
  21. * Any subsequent calls to this function will reset the timer and discard all previous calls.
  22. * @param func The function to call after the timeout
  23. * @param timeout The time in ms to wait before calling the function
  24. * @param edge Whether to call the function at the very first call ("rising" edge) or the very last call ("falling" edge, default)
  25. */
  26. export function debounce<TFunc extends (...args: TArgs[]) => void, TArgs = any>(func: TFunc, timeout = 300, edge: "rising" | "falling" = "falling") { // eslint-disable-line @typescript-eslint/no-explicit-any
  27. let timer: NodeJS.Timeout | undefined;
  28. return function(...args: TArgs[]) {
  29. if(edge === "rising") {
  30. if(!timer) {
  31. func.apply(this, args);
  32. timer = setTimeout(() => timer = undefined, timeout);
  33. }
  34. }
  35. else {
  36. clearTimeout(timer);
  37. timer = setTimeout(() => func.apply(this, args), timeout);
  38. }
  39. };
  40. }
  41. /** Options for the `fetchAdvanced()` function */
  42. export type FetchAdvancedOpts = Omit<
  43. RequestInit & Partial<{
  44. /** Timeout in milliseconds after which the fetch call will be canceled with an AbortController signal */
  45. timeout: number;
  46. }>,
  47. "signal"
  48. >;
  49. /** Calls the fetch API with special options like a timeout */
  50. export async function fetchAdvanced(input: RequestInfo | URL, options: FetchAdvancedOpts = {}) {
  51. const { timeout = 10000 } = options;
  52. let signalOpts: Partial<RequestInit> = {},
  53. id: NodeJS.Timeout | undefined = undefined;
  54. if(timeout >= 0) {
  55. const controller = new AbortController();
  56. id = setTimeout(() => controller.abort(), timeout);
  57. signalOpts = { signal: controller.signal };
  58. }
  59. const res = await fetch(input, {
  60. ...options,
  61. ...signalOpts,
  62. });
  63. clearTimeout(id);
  64. return res;
  65. }
  66. /**
  67. * Inserts the passed values into a string at the respective placeholders.
  68. * The placeholder format is `%n`, where `n` is the 1-indexed argument number.
  69. * @param input The string to insert the values into
  70. * @param values The values to insert, in order, starting at `%1`
  71. */
  72. export function insertValues(input: string, ...values: Stringifiable[]) {
  73. return input.replace(/%\d/gm, (match) => {
  74. const argIndex = Number(match.substring(1)) - 1;
  75. return (values[argIndex] ?? match)?.toString();
  76. });
  77. }
  78. /** Compresses a string or an ArrayBuffer using the provided {@linkcode compressionFormat} and returns it as a base64 string */
  79. export async function compress(input: string | ArrayBuffer, compressionFormat: CompressionFormat, outputType?: "string"): Promise<string>
  80. /** Compresses a string or an ArrayBuffer using the provided {@linkcode compressionFormat} and returns it as an ArrayBuffer */
  81. export async function compress(input: string | ArrayBuffer, compressionFormat: CompressionFormat, outputType: "arrayBuffer"): Promise<ArrayBuffer>
  82. /** Compresses a string or an ArrayBuffer using the provided {@linkcode compressionFormat} and returns it as a base64 string or ArrayBuffer, depending on what {@linkcode outputType} is set to */
  83. export async function compress(input: string | ArrayBuffer, compressionFormat: CompressionFormat, outputType: "string" | "arrayBuffer" = "string"): Promise<ArrayBuffer | string> {
  84. const byteArray = typeof input === "string" ? new TextEncoder().encode(input) : input;
  85. const comp = new CompressionStream(compressionFormat);
  86. const writer = comp.writable.getWriter();
  87. writer.write(byteArray);
  88. writer.close();
  89. const buf = await (new Response(comp.readable).arrayBuffer());
  90. return outputType === "arrayBuffer" ? buf : ab2str(buf);
  91. }
  92. /** Decompresses a previously compressed base64 string or ArrayBuffer, with the format passed by {@linkcode compressionFormat}, converted to a string */
  93. export async function decompress(input: string | ArrayBuffer, compressionFormat: CompressionFormat, outputType?: "string"): Promise<string>
  94. /** Decompresses a previously compressed base64 string or ArrayBuffer, with the format passed by {@linkcode compressionFormat}, converted to an ArrayBuffer */
  95. export async function decompress(input: string | ArrayBuffer, compressionFormat: CompressionFormat, outputType: "arrayBuffer"): Promise<ArrayBuffer>
  96. /** Decompresses a previously compressed base64 string or ArrayBuffer, with the format passed by {@linkcode compressionFormat}, converted to a string or ArrayBuffer, depending on what {@linkcode outputType} is set to */
  97. export async function decompress(input: string | ArrayBuffer, compressionFormat: CompressionFormat, outputType: "string" | "arrayBuffer" = "string"): Promise<ArrayBuffer | string> {
  98. const byteArray = typeof input === "string" ? str2ab(input) : input;
  99. const decomp = new DecompressionStream(compressionFormat);
  100. const writer = decomp.writable.getWriter();
  101. writer.write(byteArray);
  102. writer.close();
  103. const buf = await (new Response(decomp.readable).arrayBuffer());
  104. return outputType === "arrayBuffer" ? buf : new TextDecoder().decode(buf);
  105. }
  106. /** Converts an ArrayBuffer to a base64-encoded string */
  107. function ab2str(buf: ArrayBuffer) {
  108. return getUnsafeWindow().btoa(
  109. new Uint8Array(buf)
  110. .reduce((data, byte) => data + String.fromCharCode(byte), "")
  111. );
  112. }
  113. /** Converts a base64-encoded string to an ArrayBuffer representation of its bytes */
  114. function str2ab(str: string) {
  115. return Uint8Array.from(getUnsafeWindow().atob(str), c => c.charCodeAt(0));
  116. }