tiny-essentials 1.4.0 → 1.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (116) hide show
  1. package/dist/TinyEssentials.js +177 -0
  2. package/dist/TinyEssentials.min.js +1 -1
  3. package/dist/TinyPromiseQueue.js +214 -0
  4. package/dist/TinyPromiseQueue.min.js +1 -0
  5. package/dist/legacy/crypto/decrypt.d.mts +1 -0
  6. package/dist/legacy/crypto/default.d.mts +1 -0
  7. package/dist/legacy/crypto/encrypt.d.mts +1 -0
  8. package/dist/legacy/crypto/index.d.mts +1 -0
  9. package/dist/legacy/firebase/cookieSession.d.mts +1 -0
  10. package/dist/legacy/firebase/database/index.d.mts +1 -0
  11. package/dist/legacy/firebase/database/presence.d.mts +1 -0
  12. package/dist/legacy/firebase/database/saveAsync.d.mts +1 -0
  13. package/dist/legacy/firebase/databaseEscape.d.mts +1 -0
  14. package/dist/legacy/firebase/databaseLogger.d.mts +1 -0
  15. package/dist/legacy/firebase/discord/api/addGuildMember.d.mts +1 -0
  16. package/dist/legacy/firebase/discord/api/getGuildWidget.d.mts +1 -0
  17. package/dist/legacy/firebase/discord/api/getToken.d.mts +1 -0
  18. package/dist/legacy/firebase/discord/api/getUser.d.mts +1 -0
  19. package/dist/legacy/firebase/discord/api/getUserConnections.d.mts +1 -0
  20. package/dist/legacy/firebase/discord/api/getUserGuilds.d.mts +1 -0
  21. package/dist/legacy/firebase/discord/api/index.d.mts +1 -0
  22. package/dist/legacy/firebase/discord/api/refreshToken.d.mts +1 -0
  23. package/dist/legacy/firebase/discord/api/revokeToken.d.mts +1 -0
  24. package/dist/legacy/firebase/discord/config.d.mts +1 -0
  25. package/dist/legacy/firebase/discord/firebase_redirect/index.d.mts +1 -0
  26. package/dist/legacy/firebase/discord/firebase_redirect/login.d.mts +1 -0
  27. package/dist/legacy/firebase/discord/firebase_redirect/logout.d.mts +1 -0
  28. package/dist/legacy/firebase/discord/get/authURLGenerator.d.mts +1 -0
  29. package/dist/legacy/firebase/discord/get/cookie-session.d.mts +1 -0
  30. package/dist/legacy/firebase/discord/get/credentials.d.mts +1 -0
  31. package/dist/legacy/firebase/discord/get/errorValidator.d.mts +1 -0
  32. package/dist/legacy/firebase/discord/get/index.d.mts +1 -0
  33. package/dist/legacy/firebase/discord/get/randomAvatar.d.mts +1 -0
  34. package/dist/legacy/firebase/discord/http/index.d.mts +1 -0
  35. package/dist/legacy/firebase/discord/http/login.d.mts +1 -0
  36. package/dist/legacy/firebase/discord/http/logout.d.mts +1 -0
  37. package/dist/legacy/firebase/discord/http/redirect.d.mts +1 -0
  38. package/dist/legacy/firebase/discord/http/refreshToken.d.mts +1 -0
  39. package/dist/legacy/firebase/discord/index.d.mts +1 -0
  40. package/dist/legacy/firebase/discord/template/cookie-session.d.mts +1 -0
  41. package/dist/legacy/firebase/domainRedirect.d.mts +1 -0
  42. package/dist/legacy/firebase/escape.d.mts +1 -0
  43. package/dist/legacy/firebase/getDBAsync.d.mts +1 -0
  44. package/dist/legacy/firebase/getDBData.d.mts +1 -0
  45. package/dist/legacy/firebase/getDBValue.d.mts +1 -0
  46. package/dist/legacy/firebase/index.d.mts +1 -0
  47. package/dist/legacy/firebase/isEmulator.d.mts +1 -0
  48. package/dist/legacy/firebase/logger.d.mts +1 -0
  49. package/dist/legacy/firebase/mySQL.d.mts +1 -0
  50. package/dist/legacy/firebase/mysqlConnector/create.d.mts +1 -0
  51. package/dist/legacy/firebase/mysqlConnector/index.d.mts +1 -0
  52. package/dist/legacy/firebase/mysqlConnector/nextPrev.d.mts +1 -0
  53. package/dist/legacy/firebase/mysqlConnector/pagination.d.mts +1 -0
  54. package/dist/legacy/firebase/mysqlConnector/sameUser.d.mts +1 -0
  55. package/dist/legacy/firebase/transactionDBAsync.d.mts +1 -0
  56. package/dist/legacy/get/countObj.d.mts +1 -0
  57. package/dist/legacy/get/decimalColor.d.mts +1 -0
  58. package/dist/legacy/get/objType.d.mts +1 -0
  59. package/dist/legacy/get/pagination.d.mts +1 -0
  60. package/dist/legacy/get/queryUrlByName.d.mts +1 -0
  61. package/dist/legacy/get/queryUrlJSON.d.mts +1 -0
  62. package/dist/legacy/get/super_string_filter.d.mts +1 -0
  63. package/dist/legacy/get/versionCheck.d.mts +1 -0
  64. package/dist/legacy/http/HTTP-1.0.d.mts +1 -0
  65. package/dist/legacy/http/auth.d.mts +1 -0
  66. package/dist/legacy/http/check_domain.d.mts +1 -0
  67. package/dist/legacy/http/csrfTokenAnalyze.d.mts +1 -0
  68. package/dist/legacy/http/domainValidator.d.mts +1 -0
  69. package/dist/legacy/http/errorsCallback.d.mts +1 -0
  70. package/dist/legacy/http/fetch/json.d.mts +1 -0
  71. package/dist/legacy/http/fetch/text.d.mts +1 -0
  72. package/dist/legacy/http/fileCache.d.mts +1 -0
  73. package/dist/legacy/http/getDomainURL.d.mts +1 -0
  74. package/dist/legacy/http/userIP.d.mts +1 -0
  75. package/dist/legacy/index.d.mts +1 -0
  76. package/dist/legacy/libs/arraySortPositions.d.mts +1 -0
  77. package/dist/legacy/libs/capitalize.d.mts +1 -0
  78. package/dist/legacy/libs/convertBytes.d.mts +1 -0
  79. package/dist/legacy/libs/custom_module_loader.d.mts +1 -0
  80. package/dist/legacy/libs/dice.d.mts +1 -0
  81. package/dist/legacy/libs/markdown.d.mts +1 -0
  82. package/dist/legacy/libs/percentage.d.mts +1 -0
  83. package/dist/legacy/libs/regex/getLetter.d.mts +1 -0
  84. package/dist/legacy/libs/replaceAsync.d.mts +1 -0
  85. package/dist/legacy/libs/rule3.d.mts +1 -0
  86. package/dist/legacy/libs/userLevel.d.mts +1 -0
  87. package/dist/legacy/momentjs/getAge.d.mts +1 -0
  88. package/dist/legacy/momentjs/index.d.mts +1 -0
  89. package/dist/legacy/momentjs/timeDuration.d.mts +1 -0
  90. package/dist/legacy/socket.io/antiFlood/index.d.mts +1 -0
  91. package/dist/legacy/socket.io/antiFlood/install.d.mts +1 -0
  92. package/dist/legacy/socket.io/antiFlood/verify.d.mts +1 -0
  93. package/dist/legacy/socket.io/cookie-session.d.mts +1 -0
  94. package/dist/legacy/socket.io/discord.d.mts +1 -0
  95. package/dist/legacy/socket.io/index.d.mts +1 -0
  96. package/dist/v1/basics/array.d.mts +1 -0
  97. package/dist/v1/basics/clock.d.mts +1 -0
  98. package/dist/v1/basics/index.d.mts +1 -0
  99. package/dist/v1/basics/objFilter.d.mts +1 -0
  100. package/dist/v1/basics/simpleMath.d.mts +1 -0
  101. package/dist/v1/basics/text.d.mts +1 -0
  102. package/dist/v1/build/TinyLevelUp.d.mts +1 -0
  103. package/dist/v1/build/TinyPromiseQueue.cjs +7 -0
  104. package/dist/v1/build/TinyPromiseQueue.d.mts +3 -0
  105. package/dist/v1/build/TinyPromiseQueue.mjs +2 -0
  106. package/dist/v1/index.cjs +2 -0
  107. package/dist/v1/index.d.mts +3 -1
  108. package/dist/v1/index.mjs +2 -1
  109. package/dist/v1/libs/TinyPromiseQueue.cjs +175 -0
  110. package/dist/v1/libs/TinyPromiseQueue.d.mts +63 -0
  111. package/dist/v1/libs/TinyPromiseQueue.mjs +159 -0
  112. package/docs/README.md +5 -0
  113. package/docs/basics/asyncReplace.md +39 -0
  114. package/docs/libs/TinyLevelUp.md +108 -0
  115. package/docs/libs/TinyPromiseQueue.md +126 -0
  116. package/package.json +4 -2
@@ -0,0 +1,175 @@
1
+ 'use strict';
2
+
3
+ /**
4
+ * A queue system for managing and executing asynchronous tasks sequentially, one at a time.
5
+ *
6
+ * Tasks can be delayed, reordered, canceled, and processed in strict order. The queue ensures that each task
7
+ * is executed after the previous one finishes, and any task can be skipped or canceled if needed.
8
+ *
9
+ * @class
10
+ */
11
+ class TinyPromiseQueue {
12
+ /**
13
+ * @typedef {Object} QueuedTask
14
+ * @property {() => Promise<any>} task - The async task to execute.
15
+ * @property {(value: any) => any} resolve - The resolve function from the Promise.
16
+ * @property {(reason?: any) => any} reject - The reject function from the Promise.
17
+ * @property {string|undefined} [id] - Optional identifier for the task.
18
+ * @property {number|null|undefined} [delay] - Optional delay (in ms) before the task is executed.
19
+ */
20
+
21
+ /** @type {Array<QueuedTask>} */
22
+ #queue = [];
23
+ #running = false;
24
+ /** @type {Record<string, *>} */
25
+ #timeouts = {};
26
+ /** @type {Set<string>} */
27
+ #blacklist = new Set();
28
+
29
+ /**
30
+ * Returns whether the queue is currently processing a task.
31
+ *
32
+ * @returns {boolean}
33
+ */
34
+ isRunning() {
35
+ return this.#running;
36
+ }
37
+
38
+ /**
39
+ * Processes the next task in the queue if not already running.
40
+ * Ensures tasks are executed in order, one at a time.
41
+ *
42
+ * @returns {Promise<void>}
43
+ */
44
+ async #processQueue() {
45
+ if (this.#running || this.#queue.length === 0) return;
46
+ this.#running = true;
47
+ const data = this.#queue.shift();
48
+ if (
49
+ data &&
50
+ typeof data.task === 'function' &&
51
+ typeof data.resolve === 'function' &&
52
+ typeof data.reject === 'function'
53
+ ) {
54
+ const { task, resolve, reject, delay, id } = data;
55
+ try {
56
+ if (delay && id) {
57
+ await new Promise((resolveDelay) => {
58
+ const timeoutId = setTimeout(() => {
59
+ delete this.#timeouts[id];
60
+ resolveDelay(null);
61
+ }, delay);
62
+ this.#timeouts[id] = timeoutId;
63
+ });
64
+ }
65
+
66
+ if (id && this.#blacklist.has(id)) {
67
+ reject(new Error('The function was canceled on TinyPromiseQueue.'));
68
+ this.#blacklist.delete(id);
69
+ this.#running = false;
70
+ this.#processQueue();
71
+ return;
72
+ }
73
+
74
+ const result = await task();
75
+ resolve(result);
76
+ } catch (error) {
77
+ reject(error);
78
+ } finally {
79
+ this.#running = false;
80
+ this.#processQueue();
81
+ }
82
+ }
83
+ }
84
+
85
+ /**
86
+ * Returns the index of a task by its ID.
87
+ *
88
+ * @param {string} id The ID of the task to locate.
89
+ * @returns {number} The index of the task in the queue, or -1 if not found.
90
+ */
91
+ getIndexById(id) {
92
+ return this.#queue.findIndex((item) => item.id === id);
93
+ }
94
+
95
+ /**
96
+ * Returns a list of IDs for all tasks currently in the queue.
97
+ *
98
+ * @returns {{ index: number, id: string }[]} An array of task IDs currently queued.
99
+ */
100
+ getQueuedIds() {
101
+ // @ts-ignore
102
+ return this.#queue
103
+ .map((item, index) => ({ index, id: item.id }))
104
+ .filter((entry) => typeof entry.id === 'string');
105
+ }
106
+
107
+ /**
108
+ * Reorders a task in the queue from one index to another.
109
+ *
110
+ * @param {number} fromIndex The current index of the task to move.
111
+ * @param {number} toIndex The index where the task should be placed.
112
+ */
113
+ reorderQueue(fromIndex, toIndex) {
114
+ if (
115
+ typeof fromIndex !== 'number' ||
116
+ typeof toIndex !== 'number' ||
117
+ fromIndex < 0 ||
118
+ toIndex < 0 ||
119
+ fromIndex >= this.#queue.length ||
120
+ toIndex >= this.#queue.length
121
+ )
122
+ return;
123
+ const [item] = this.#queue.splice(fromIndex, 1);
124
+ this.#queue.splice(toIndex, 0, item);
125
+ }
126
+
127
+ /**
128
+ * Adds a new async task to the queue and ensures it runs in order after previous tasks.
129
+ * Optionally, a delay can be added before the task is executed.
130
+ *
131
+ * If the task is canceled before execution, it will be rejected with the message:
132
+ * "The function was canceled on TinyPromiseQueue."
133
+ *
134
+ * @param {(...args: any[]) => Promise<any>} task A function that returns a Promise to be executed sequentially.
135
+ * @param {number|null} [delay] Optional delay (in ms) before the task is executed.
136
+ * @param {string} [id] Optional ID to identify the task in the queue.
137
+ * @returns {Promise<any>} A Promise that resolves or rejects with the result of the task once it's processed.
138
+ */
139
+ enqueue(task, delay, id) {
140
+ return new Promise((resolve, reject) => {
141
+ this.#queue.push({ task, resolve, reject, id, delay });
142
+ this.#processQueue();
143
+ });
144
+ }
145
+
146
+ /**
147
+ * Cancels a scheduled delay and removes the task from the queue.
148
+ * Adds the ID to a blacklist so the task is skipped if already being processed.
149
+ *
150
+ * @param {string} id The ID of the task to cancel.
151
+ * @returns {boolean} True if a delay was cancelled and the task was removed.
152
+ */
153
+ cancelTask(id) {
154
+ if (!id) return false;
155
+ let cancelled = false;
156
+
157
+ if (id in this.#timeouts) {
158
+ clearTimeout(this.#timeouts[id]);
159
+ delete this.#timeouts[id];
160
+ cancelled = true;
161
+ }
162
+
163
+ const index = this.getIndexById(id);
164
+ if (index !== -1) {
165
+ this.#queue.splice(index, 1);
166
+ cancelled = true;
167
+ }
168
+
169
+ if (cancelled) this.#blacklist.add(id);
170
+
171
+ return cancelled;
172
+ }
173
+ }
174
+
175
+ module.exports = TinyPromiseQueue;
@@ -0,0 +1,63 @@
1
+ export default TinyPromiseQueue;
2
+ /**
3
+ * A queue system for managing and executing asynchronous tasks sequentially, one at a time.
4
+ *
5
+ * Tasks can be delayed, reordered, canceled, and processed in strict order. The queue ensures that each task
6
+ * is executed after the previous one finishes, and any task can be skipped or canceled if needed.
7
+ *
8
+ * @class
9
+ */
10
+ declare class TinyPromiseQueue {
11
+ /**
12
+ * Returns whether the queue is currently processing a task.
13
+ *
14
+ * @returns {boolean}
15
+ */
16
+ isRunning(): boolean;
17
+ /**
18
+ * Returns the index of a task by its ID.
19
+ *
20
+ * @param {string} id The ID of the task to locate.
21
+ * @returns {number} The index of the task in the queue, or -1 if not found.
22
+ */
23
+ getIndexById(id: string): number;
24
+ /**
25
+ * Returns a list of IDs for all tasks currently in the queue.
26
+ *
27
+ * @returns {{ index: number, id: string }[]} An array of task IDs currently queued.
28
+ */
29
+ getQueuedIds(): {
30
+ index: number;
31
+ id: string;
32
+ }[];
33
+ /**
34
+ * Reorders a task in the queue from one index to another.
35
+ *
36
+ * @param {number} fromIndex The current index of the task to move.
37
+ * @param {number} toIndex The index where the task should be placed.
38
+ */
39
+ reorderQueue(fromIndex: number, toIndex: number): void;
40
+ /**
41
+ * Adds a new async task to the queue and ensures it runs in order after previous tasks.
42
+ * Optionally, a delay can be added before the task is executed.
43
+ *
44
+ * If the task is canceled before execution, it will be rejected with the message:
45
+ * "The function was canceled on TinyPromiseQueue."
46
+ *
47
+ * @param {(...args: any[]) => Promise<any>} task A function that returns a Promise to be executed sequentially.
48
+ * @param {number|null} [delay] Optional delay (in ms) before the task is executed.
49
+ * @param {string} [id] Optional ID to identify the task in the queue.
50
+ * @returns {Promise<any>} A Promise that resolves or rejects with the result of the task once it's processed.
51
+ */
52
+ enqueue(task: (...args: any[]) => Promise<any>, delay?: number | null, id?: string): Promise<any>;
53
+ /**
54
+ * Cancels a scheduled delay and removes the task from the queue.
55
+ * Adds the ID to a blacklist so the task is skipped if already being processed.
56
+ *
57
+ * @param {string} id The ID of the task to cancel.
58
+ * @returns {boolean} True if a delay was cancelled and the task was removed.
59
+ */
60
+ cancelTask(id: string): boolean;
61
+ #private;
62
+ }
63
+ //# sourceMappingURL=TinyPromiseQueue.d.mts.map
@@ -0,0 +1,159 @@
1
+ /**
2
+ * A queue system for managing and executing asynchronous tasks sequentially, one at a time.
3
+ *
4
+ * Tasks can be delayed, reordered, canceled, and processed in strict order. The queue ensures that each task
5
+ * is executed after the previous one finishes, and any task can be skipped or canceled if needed.
6
+ *
7
+ * @class
8
+ */
9
+ class TinyPromiseQueue {
10
+ /**
11
+ * @typedef {Object} QueuedTask
12
+ * @property {() => Promise<any>} task - The async task to execute.
13
+ * @property {(value: any) => any} resolve - The resolve function from the Promise.
14
+ * @property {(reason?: any) => any} reject - The reject function from the Promise.
15
+ * @property {string|undefined} [id] - Optional identifier for the task.
16
+ * @property {number|null|undefined} [delay] - Optional delay (in ms) before the task is executed.
17
+ */
18
+ /** @type {Array<QueuedTask>} */
19
+ #queue = [];
20
+ #running = false;
21
+ /** @type {Record<string, *>} */
22
+ #timeouts = {};
23
+ /** @type {Set<string>} */
24
+ #blacklist = new Set();
25
+ /**
26
+ * Returns whether the queue is currently processing a task.
27
+ *
28
+ * @returns {boolean}
29
+ */
30
+ isRunning() {
31
+ return this.#running;
32
+ }
33
+ /**
34
+ * Processes the next task in the queue if not already running.
35
+ * Ensures tasks are executed in order, one at a time.
36
+ *
37
+ * @returns {Promise<void>}
38
+ */
39
+ async #processQueue() {
40
+ if (this.#running || this.#queue.length === 0)
41
+ return;
42
+ this.#running = true;
43
+ const data = this.#queue.shift();
44
+ if (data &&
45
+ typeof data.task === 'function' &&
46
+ typeof data.resolve === 'function' &&
47
+ typeof data.reject === 'function') {
48
+ const { task, resolve, reject, delay, id } = data;
49
+ try {
50
+ if (delay && id) {
51
+ await new Promise((resolveDelay) => {
52
+ const timeoutId = setTimeout(() => {
53
+ delete this.#timeouts[id];
54
+ resolveDelay(null);
55
+ }, delay);
56
+ this.#timeouts[id] = timeoutId;
57
+ });
58
+ }
59
+ if (id && this.#blacklist.has(id)) {
60
+ reject(new Error('The function was canceled on TinyPromiseQueue.'));
61
+ this.#blacklist.delete(id);
62
+ this.#running = false;
63
+ this.#processQueue();
64
+ return;
65
+ }
66
+ const result = await task();
67
+ resolve(result);
68
+ }
69
+ catch (error) {
70
+ reject(error);
71
+ }
72
+ finally {
73
+ this.#running = false;
74
+ this.#processQueue();
75
+ }
76
+ }
77
+ }
78
+ /**
79
+ * Returns the index of a task by its ID.
80
+ *
81
+ * @param {string} id The ID of the task to locate.
82
+ * @returns {number} The index of the task in the queue, or -1 if not found.
83
+ */
84
+ getIndexById(id) {
85
+ return this.#queue.findIndex((item) => item.id === id);
86
+ }
87
+ /**
88
+ * Returns a list of IDs for all tasks currently in the queue.
89
+ *
90
+ * @returns {{ index: number, id: string }[]} An array of task IDs currently queued.
91
+ */
92
+ getQueuedIds() {
93
+ // @ts-ignore
94
+ return this.#queue
95
+ .map((item, index) => ({ index, id: item.id }))
96
+ .filter((entry) => typeof entry.id === 'string');
97
+ }
98
+ /**
99
+ * Reorders a task in the queue from one index to another.
100
+ *
101
+ * @param {number} fromIndex The current index of the task to move.
102
+ * @param {number} toIndex The index where the task should be placed.
103
+ */
104
+ reorderQueue(fromIndex, toIndex) {
105
+ if (typeof fromIndex !== 'number' ||
106
+ typeof toIndex !== 'number' ||
107
+ fromIndex < 0 ||
108
+ toIndex < 0 ||
109
+ fromIndex >= this.#queue.length ||
110
+ toIndex >= this.#queue.length)
111
+ return;
112
+ const [item] = this.#queue.splice(fromIndex, 1);
113
+ this.#queue.splice(toIndex, 0, item);
114
+ }
115
+ /**
116
+ * Adds a new async task to the queue and ensures it runs in order after previous tasks.
117
+ * Optionally, a delay can be added before the task is executed.
118
+ *
119
+ * If the task is canceled before execution, it will be rejected with the message:
120
+ * "The function was canceled on TinyPromiseQueue."
121
+ *
122
+ * @param {(...args: any[]) => Promise<any>} task A function that returns a Promise to be executed sequentially.
123
+ * @param {number|null} [delay] Optional delay (in ms) before the task is executed.
124
+ * @param {string} [id] Optional ID to identify the task in the queue.
125
+ * @returns {Promise<any>} A Promise that resolves or rejects with the result of the task once it's processed.
126
+ */
127
+ enqueue(task, delay, id) {
128
+ return new Promise((resolve, reject) => {
129
+ this.#queue.push({ task, resolve, reject, id, delay });
130
+ this.#processQueue();
131
+ });
132
+ }
133
+ /**
134
+ * Cancels a scheduled delay and removes the task from the queue.
135
+ * Adds the ID to a blacklist so the task is skipped if already being processed.
136
+ *
137
+ * @param {string} id The ID of the task to cancel.
138
+ * @returns {boolean} True if a delay was cancelled and the task was removed.
139
+ */
140
+ cancelTask(id) {
141
+ if (!id)
142
+ return false;
143
+ let cancelled = false;
144
+ if (id in this.#timeouts) {
145
+ clearTimeout(this.#timeouts[id]);
146
+ delete this.#timeouts[id];
147
+ cancelled = true;
148
+ }
149
+ const index = this.getIndexById(id);
150
+ if (index !== -1) {
151
+ this.#queue.splice(index, 1);
152
+ cancelled = true;
153
+ }
154
+ if (cancelled)
155
+ this.#blacklist.add(id);
156
+ return cancelled;
157
+ }
158
+ }
159
+ export default TinyPromiseQueue;
package/docs/README.md CHANGED
@@ -17,6 +17,11 @@ This folder contains the core scripts we have worked on so far. Each file is a m
17
17
  - 🧠 **[objFilter.md](./basics/objFilter.md)** — Type detection, extension, and analysis made easy with simple and extensible type validation.
18
18
  - 🔢 **[simpleMath.md](./basics/simpleMath.md)** — A collection of simple math utilities for calculations like the Rule of Three and percentages.
19
19
  - ✍️ **[text.md](./basics/text.md)** — A utility for transforming text into title case formats, with multiple options for capitalization.
20
+ - 🔄 **[asyncReplace.md](./basics/asyncReplace.md)** — Asynchronously replaces matches in a string using a regex and an async function.
21
+
22
+ ### 2. **`libs/`**
23
+ - 🗂️ **[TinyPromiseQueue.md](./libs/TinyPromiseQueue.md)** — A class that allows sequential execution of asynchronous tasks, supporting task delays, cancellation, and queue management.
24
+ - 🏅 **[TinyLevelUp.md](./libs/TinyLevelUp.md)** — A class to manage user level-up logic based on experience points, providing methods for experience validation, addition, removal, and calculation.
20
25
 
21
26
  ---
22
27
 
@@ -0,0 +1,39 @@
1
+ ## `asyncReplace(str, regex, asyncFn)` 🔄
2
+
3
+ Asynchronously replaces matches in a string using a regular expression and an async function.
4
+
5
+ This function performs replacements on a string, allowing each match to be asynchronously replaced by calling an asynchronous function for each match. The asynchronous function should return a replacement value for each match and will receive the same arguments as the standard `replace` callback.
6
+
7
+ ### Parameters:
8
+
9
+ - `str` (`string`): The input string to perform replacements on.
10
+ - `regex` (`RegExp`): The regular expression used to match substrings for replacement.
11
+ - `asyncFn` (`Function`): An asynchronous function that returns a replacement for each match.
12
+ - It receives the same arguments as the standard `replace` callback (the matched substring and the matched string's groups).
13
+ - The function should return a `Promise` that resolves to the replacement value for that match.
14
+
15
+ ### Returns:
16
+ - `Promise<string>`: A promise that resolves to the resulting string with all async replacements applied.
17
+
18
+ ### Example:
19
+
20
+ ```javascript
21
+ await asyncReplace("Hello @user1 and @user2!", /@\w+/g, async (mention) => {
22
+ return await getUserNameFromMention(mention);
23
+ });
24
+ ```
25
+
26
+ In this example, each `@user` mention is asynchronously replaced by the value returned from `getUserNameFromMention`.
27
+
28
+ ### Description:
29
+
30
+ This function will:
31
+ 1. Use a regular expression (`regex`) to find all matches in the input string (`str`).
32
+ 2. For each match, it will invoke the provided asynchronous function (`asyncFn`), which should return the replacement value.
33
+ 3. Once all promises are resolved, it replaces the original matches in the string with the resolved values.
34
+
35
+ This is useful for scenarios where you need to replace parts of a string based on dynamic data (like fetching usernames from a server for each mention in a message).
36
+
37
+ ### Notes:
38
+ - The replacements are performed asynchronously, ensuring non-blocking behavior when dealing with large or external data sources.
39
+ - The function utilizes `Promise.all` to handle multiple asynchronous operations concurrently before replacing the matches in the original string.
@@ -0,0 +1,108 @@
1
+
2
+ ### TinyLevelUp 🎮
3
+
4
+ This class manages user level-up logic based on experience points. It provides methods to handle experience points (exp) adjustments, level progression, and random experience generation.
5
+
6
+ #### Constructor 🛠️
7
+
8
+ - **`constructor(giveExp: number, expLevel: number)`**
9
+ Initializes the class with the base experience value for random experience generation and the base experience required to level up.
10
+
11
+ - `giveExp` (`number`): The base experience value used for random experience generation. 🎲
12
+ - `expLevel` (`number`): The base experience required to level up for each level. 📈
13
+
14
+ #### Methods 🔧
15
+
16
+ - **`expValidator(user: UserEditor)`**
17
+ Validates and adjusts the user's level based on their current experience. If the user's experience is above or below the required threshold, their level is adjusted accordingly. ⚖️
18
+
19
+ - `user` (`UserEditor`): The user object containing `exp` (experience), `level` (current level), and `totalExp` (total experience). 👤
20
+
21
+ - **Returns**: `UserResult` - The updated user object. 🔄
22
+
23
+ - **`getTotalExp(user: { exp: number, level: number })`**
24
+ Calculates the total experience based on the user's level and experience. 📊
25
+
26
+ - `user` (`Object`): The user object containing `exp` (experience) and `level` (level). 👤
27
+
28
+ - **Returns**: `number` - The total experience of the user. 🔢
29
+
30
+ - **`expGenerator(multi: number = 1)`**
31
+ Generates random experience points based on a configured multiplier. 🎲
32
+
33
+ - `multi` (`number`): A multiplier for experience generation. Default is `1`. 💯
34
+
35
+ - **Returns**: `number` - The generated experience points. 💥
36
+
37
+ - **`progress(user: { level: number })`**
38
+ Gets the experience points required to reach the next level. ⏩
39
+
40
+ - `user` (`Object`): The user object containing the `level`. 👤
41
+
42
+ - **Returns**: `number` - The experience required for the next level. 📈
43
+
44
+ - **`getProgress(user: { level: number })`**
45
+ An alias for `progress`. Returns the experience points required to reach the next level. ⏩
46
+
47
+ - `user` (`Object`): The user object containing the `level`. 👤
48
+
49
+ - **Returns**: `number` - The experience required for the next level. 📈
50
+
51
+ - **`set(user: UserEditor, value: number)`**
52
+ Sets the user's experience value and adjusts their level if necessary. 📝
53
+
54
+ - `user` (`UserEditor`): The user object containing `exp`, `level`, and `totalExp`. 👤
55
+ - `value` (`number`): The new experience value to set for the user. 💡
56
+
57
+ - **Returns**: `UserResult` - The updated user object. 🔄
58
+
59
+ - **`give(user: UserEditor, extraExp: number = 0, type: 'add' | 'extra' = 'add', multi: number = 1)`**
60
+ Adds experience to the user and adjusts their level if necessary. Experience can be added with or without a multiplier. ➕
61
+
62
+ - `user` (`UserEditor`): The user object containing `exp`, `level`, and `totalExp`. 👤
63
+ - `extraExp` (`number`): Additional experience to be added. 💯
64
+ - `type` (`'add' | 'extra'`): Type of experience addition. `'add'` adds random experience, while `'extra'` adds specified experience. 🔧
65
+ - `multi` (`number`): Multiplier for experience generation. Default is `1`. 💥
66
+
67
+ - **Returns**: `UserResult` - The updated user object. 🔄
68
+
69
+ - **`remove(user: UserEditor, extraExp: number = 0, type: 'add' | 'extra' = 'add', multi: number = 1)`**
70
+ Removes experience from the user and adjusts their level if necessary. Experience can be removed with or without a multiplier. ➖
71
+
72
+ - `user` (`UserEditor`): The user object containing `exp`, `level`, and `totalExp`. 👤
73
+ - `extraExp` (`number`): Additional experience to be removed. 💣
74
+ - `type` (`'add' | 'extra'`): Type of experience removal. `'add'` removes random experience, while `'extra'` removes specified experience. 🔧
75
+ - `multi` (`number`): Multiplier for experience generation. Default is `1`. 💥
76
+
77
+ - **Returns**: `UserResult` - The updated user object. 🔄
78
+
79
+ ### Type Definitions 📚
80
+
81
+ - **`UserResult`**
82
+ Represents the structure of a user object after level validation. 🧑‍💻
83
+
84
+ - `exp` (`number`): The user's experience. 🎯
85
+ - `level` (`number`): The user's current level. 🏆
86
+ - `totalExp` (`number`): The user's total experience. 📊
87
+
88
+ - **`UserEditor`**
89
+ Represents the user object before level validation. 🔧
90
+
91
+ - `exp` (`number`): The user's experience. 🎯
92
+ - `level` (`number`): The user's current level. 🏆
93
+ - `totalExp` (`any`): The user's total experience (can be calculated using `getTotalExp`). 📊
94
+
95
+ ### Example Usage 💡
96
+
97
+ ```javascript
98
+ const user = { exp: 50, level: 1, totalExp: 50 };
99
+ const levelUpSystem = new TinyLevelUp(100, 1000);
100
+
101
+ // Add experience and check updated user stats
102
+ levelUpSystem.give(user);
103
+ console.log(user); // { exp: 112, level: 1, totalExp: 112 }
104
+ ```
105
+
106
+ ---
107
+
108
+ This class can be used to manage user experience points and level-ups in any system requiring user progression logic. 🚀
@@ -0,0 +1,126 @@
1
+ # `TinyPromiseQueue` Documentation 🎉
2
+
3
+ `TinyPromiseQueue` is a queue system designed to manage and execute asynchronous tasks in a sequential, one-at-a-time order. Tasks are executed in the order they are added to the queue, with support for optional delays ⏳, task cancellation ❌, and task reordering 🔄.
4
+
5
+ ---
6
+
7
+ ## Properties 🏠
8
+
9
+ - **`#queue`**: The internal queue array that holds all the tasks.
10
+ - **`#running`**: A flag indicating whether the queue is currently processing a task.
11
+ - **`#timeouts`**: An object storing timeouts for scheduled delays.
12
+ - **`#blacklist`**: A set of task IDs that should be skipped if already being processed or canceled.
13
+
14
+ ---
15
+
16
+ ## Methods 🛠️
17
+
18
+ ### `isRunning()` 🏃‍♀️
19
+
20
+ Returns whether the queue is currently processing a task.
21
+
22
+ #### Returns:
23
+ - `boolean`: `true` if the queue is processing a task, otherwise `false`.
24
+
25
+ ### `getIndexById(id)` 🔍
26
+
27
+ Returns the index of a task in the queue by its ID.
28
+
29
+ #### Parameters:
30
+ - `id` (`string`): The ID of the task to locate.
31
+
32
+ #### Returns:
33
+ - `number`: The index of the task in the queue, or `-1` if not found.
34
+
35
+ ### `getQueuedIds()` 📋
36
+
37
+ Returns a list of IDs for all tasks currently in the queue.
38
+
39
+ #### Returns:
40
+ - `Array<{ index: number, id: string }>`: An array of task IDs and their corresponding indices.
41
+
42
+ ### `reorderQueue(fromIndex, toIndex)` 🔄
43
+
44
+ Reorders a task in the queue from one index to another.
45
+
46
+ #### Parameters:
47
+ - `fromIndex` (`number`): The current index of the task to move.
48
+ - `toIndex` (`number`): The index where the task should be placed.
49
+
50
+ #### Returns:
51
+ - `void`: This method does not return anything.
52
+
53
+ ### `enqueue(task, delay, id)` ⏳
54
+
55
+ Adds a new async task to the queue and ensures it runs in order after previous tasks. Optionally, a delay can be added before the task is executed.
56
+
57
+ If the task is canceled before execution, it will be rejected with the message:
58
+ **"The function was canceled on TinyPromiseQueue."**
59
+
60
+ #### Parameters:
61
+ - `task` (`Function`): A function that returns a `Promise` to be executed sequentially.
62
+ - `delay` (`number|null`): Optional delay (in ms) before the task is executed.
63
+ - `id` (`string`): Optional ID to identify the task in the queue.
64
+
65
+ #### Returns:
66
+ - `Promise<any>`: A promise that resolves or rejects with the result of the task once it's processed.
67
+
68
+ ### `cancelTask(id)` ❌
69
+
70
+ Cancels a scheduled delay and removes the task from the queue. Adds the ID to a blacklist so the task is skipped if already being processed.
71
+
72
+ #### Parameters:
73
+ - `id` (`string`): The ID of the task to cancel.
74
+
75
+ #### Returns:
76
+ - `boolean`: `true` if a delay was cancelled and the task was removed, otherwise `false`.
77
+
78
+ ---
79
+
80
+ ## Usage Example 💻
81
+
82
+ ```js
83
+ import { TinyPromiseQueue } from './TinyPromiseQueue';
84
+
85
+ const queue = new TinyPromiseQueue();
86
+
87
+ // Helper function to create simple tasks with logs
88
+ function createTask(name, duration = 500) {
89
+ return () => new Promise((resolve) => {
90
+ console.log(`Started task: ${name}`);
91
+ setTimeout(() => {
92
+ console.log(`Finished task: ${name}`);
93
+ resolve(name);
94
+ }, duration);
95
+ });
96
+ }
97
+
98
+ // Enqueue 3 tasks
99
+ queue.enqueue(createTask('A'), 100, 'taskA');
100
+ queue.enqueue(createTask('B'), 0, 'taskB');
101
+ queue.enqueue(createTask('C'), 0, 'taskC');
102
+
103
+ // Wait for 50ms and cancel taskB
104
+ setTimeout(() => {
105
+ const success = queue.cancelTask('taskB');
106
+ console.log('Canceled taskB:', success); // true if cancelled
107
+ }, 50);
108
+
109
+ // List the remaining IDs in the queue
110
+ setTimeout(() => {
111
+ const ids = queue.getQueuedIds();
112
+ console.log('Queued IDs:', ids);
113
+ }, 60);
114
+ ```
115
+
116
+ ### Explanation 🧩:
117
+ 1. **Task Creation**: Tasks are created with a name and an optional duration (in ms). The task logs its start and finish times 🕰️.
118
+ 2. **Task Execution**: Tasks are enqueued one at a time, ensuring they run in the order they were added 🔁.
119
+ 3. **Cancellation**: After 50ms, taskB is canceled, demonstrating the ability to remove a task from the queue ❌.
120
+ 4. **Remaining Tasks**: The remaining tasks in the queue are logged after 60ms 📊.
121
+
122
+ ---
123
+
124
+ ## Conclusion 🎯
125
+
126
+ `TinyPromiseQueue` provides a simple and effective way to manage a sequence of asynchronous tasks. With its support for delays ⏳, task cancellation ❌, and reordering 🔄, it allows for efficient control over task execution in JavaScript.