@jsnw/common-utils 1.0.0 → 1.2.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.
package/dist/index.mjs ADDED
@@ -0,0 +1,217 @@
1
+ //#region src/noop.ts
2
+ /**
3
+ * A no-operation function that performs no action.
4
+ * This function can be used as a placeholder or default value
5
+ * where a function is required but no operation is necessary.
6
+ *
7
+ * @returns {void}
8
+ */
9
+ const noop = () => {};
10
+ //#endregion
11
+ //#region src/ignorePromise.ts
12
+ /**
13
+ * Accepts a promise and ensures that its resolution or rejection is ignored.
14
+ *
15
+ * @param {Promise<any>} promise - The promise to be ignored.
16
+ */
17
+ const ignorePromise = (promise) => {
18
+ promise.then(noop).catch(noop);
19
+ };
20
+ //#endregion
21
+ //#region src/chunk.ts
22
+ /**
23
+ * Splits an array into smaller arrays of a specified size.
24
+ *
25
+ * @template T
26
+ * @param {T[]} arr - The array to be split into chunks.
27
+ * @param {number} chunk_size - The size of each chunk.
28
+ * @returns {T[][]} An array containing the chunks.
29
+ */
30
+ const chunk = (arr, chunk_size) => {
31
+ if (chunk_size <= 0) throw new TypeError("Chunk size should be greater than 0");
32
+ return Array.from({ length: Math.ceil(arr.length / chunk_size) }, (_, i) => arr.slice(i * chunk_size, i * chunk_size + chunk_size));
33
+ };
34
+ //#endregion
35
+ //#region src/chunkStr.ts
36
+ /**
37
+ * Splits a string into chunks of a specified size
38
+ *
39
+ * @param {string} str - The string to be split into chunks
40
+ * @param {number} chunkSize - The size of each chunk
41
+ * @returns {string[]} An array containing the chunks
42
+ */
43
+ function chunkStr(str, chunkSize) {
44
+ if (chunkSize <= 0) throw new TypeError("Chunk size should be greater than 0");
45
+ return Array.from({ length: Math.ceil(str.length / chunkSize) }, (_, i) => str.slice(i * chunkSize, i * chunkSize + chunkSize));
46
+ }
47
+ //#endregion
48
+ //#region src/wait.ts
49
+ /**
50
+ * Waits asynchronously for the specified amount of milliseconds before resolving.
51
+ *
52
+ * @param {number} wait_ms - The number of milliseconds to wait. If less than 1, the promise resolves immediately.
53
+ * @param {AbortSignal} [signal]
54
+ * @returns {Promise<void>} A promise that resolves after the specified wait time.
55
+ */
56
+ const wait = (wait_ms, signal) => {
57
+ if (wait_ms < 1) return Promise.resolve();
58
+ if (!Number.isFinite(wait_ms) && !signal) throw new TypeError("Invalid wait_ms: must be a finite number (or you should provide an AbortSignal as a second argument)");
59
+ if (signal?.aborted) return Promise.resolve();
60
+ if (!signal) return new Promise((resolve) => setTimeout(resolve, wait_ms));
61
+ return new Promise((resolve) => {
62
+ let timer_ref = null;
63
+ const on_abort = () => {
64
+ if (timer_ref) clearTimeout(timer_ref);
65
+ resolve();
66
+ };
67
+ signal.addEventListener("abort", on_abort, { once: true });
68
+ timer_ref = setTimeout(() => {
69
+ signal.removeEventListener("abort", on_abort);
70
+ resolve();
71
+ }, wait_ms);
72
+ });
73
+ };
74
+ //#endregion
75
+ //#region src/isObjectEmpty.ts
76
+ /**
77
+ * @param {object} obj
78
+ * @returns {boolean}
79
+ */
80
+ function isObjectEmpty(obj) {
81
+ if (Array.isArray(obj)) return obj.length === 0;
82
+ for (const key in obj) if (Object.prototype.hasOwnProperty.call(obj, key)) return false;
83
+ return true;
84
+ }
85
+ //#endregion
86
+ //#region src/createInFlightDeduper.ts
87
+ /**
88
+ * Creates a deduplicator for in-flight promises or sync functions.
89
+ * Prevents duplicate executions for the same key while a promise is pending.
90
+ * Clears the entry after settlement.
91
+ * @returns {InFlightDeduper}
92
+ */
93
+ function createInFlightDeduper() {
94
+ const __promises = /* @__PURE__ */ new Map();
95
+ function use(key, fn) {
96
+ let promise = __promises.get(key);
97
+ if (promise) return promise;
98
+ promise = Promise.resolve(fn()).finally(() => {
99
+ __promises.delete(key);
100
+ });
101
+ __promises.set(key, promise);
102
+ return promise;
103
+ }
104
+ return { use };
105
+ }
106
+ //#endregion
107
+ //#region src/resultify.ts
108
+ /**
109
+ * Executes a function and returns its result as a tuple `[value, error]`.
110
+ * Works with both sync and async functions. Never throws.
111
+ *
112
+ * @template {() => any} F
113
+ * @template {Error} E
114
+ * @param {F} fn
115
+ */
116
+ function resultify(fn) {
117
+ try {
118
+ const promiseOrResult = fn();
119
+ if (promiseOrResult instanceof Promise) return promiseOrResult.then((res) => [res, null]).catch((err) => [null, err]);
120
+ return [promiseOrResult, null];
121
+ } catch (e) {
122
+ return [null, e];
123
+ }
124
+ }
125
+ //#endregion
126
+ //#region src/monitor.ts
127
+ var Monitor = class Monitor {
128
+ marks = /* @__PURE__ */ new Map();
129
+ /**
130
+ * @template {(...args: any[]) => any} F
131
+ * @param {F} fn
132
+ * @returns {ReturnType<F> extends Promise<any> ? Promise<number> : number}
133
+ */
134
+ static measureFunctionTime(fn) {
135
+ const timeStart = Date.now();
136
+ const promiseOrResult = fn();
137
+ if (promiseOrResult instanceof Promise) return Promise.resolve(promiseOrResult).then(() => Date.now() - timeStart);
138
+ return Date.now() - timeStart;
139
+ }
140
+ /**
141
+ * @param {string} label
142
+ * @returns {Monitor}
143
+ */
144
+ static autoStart(label) {
145
+ const instance = new Monitor();
146
+ instance.start(label);
147
+ return instance;
148
+ }
149
+ constructor() {}
150
+ /**
151
+ * @param {string} label
152
+ */
153
+ start(label) {
154
+ if (!this.marks.has(label)) this.marks.set(label, [[Date.now()]]);
155
+ else return;
156
+ }
157
+ /**
158
+ * @param {string} label
159
+ * @param {string} [description]
160
+ */
161
+ mark(label, description) {
162
+ if (!this.marks.has(label)) throw new TypeError(`Label ${label} not found`);
163
+ this.marks.get(label).push([Date.now(), description]);
164
+ }
165
+ /**
166
+ * @param {string} label
167
+ * @returns {MonitorResult}
168
+ */
169
+ stop(label) {
170
+ const endTime = Date.now();
171
+ const marks = this.marks.get(label);
172
+ if (!marks) throw new TypeError(`Label ${label} not found`);
173
+ const [firstTs] = marks[0], processedMarks = [];
174
+ for (let i = 1; i < marks.length; i++) processedMarks.push({
175
+ ts: marks[i][0],
176
+ diff: marks[i][0] - firstTs,
177
+ description: marks[i][1]
178
+ });
179
+ this.marks.delete(label);
180
+ return {
181
+ marks: processedMarks,
182
+ startTs: firstTs,
183
+ stopTs: endTime,
184
+ totalTime: endTime - firstTs
185
+ };
186
+ }
187
+ };
188
+ //#endregion
189
+ //#region src/trySettlePromises.ts
190
+ const trySettlePromises = async (promises, onError) => {
191
+ onError = onError && typeof onError === "function" ? onError : noop;
192
+ const results = await Promise.allSettled(promises.map((v) => Array.isArray(v) ? v[0] : v));
193
+ for (let i = 0; i < results.length; i++) {
194
+ const res = results[i];
195
+ const entry = promises[i];
196
+ if (res.status === "rejected") try {
197
+ onError({
198
+ reason: res.reason,
199
+ message: Array.isArray(entry) ? entry[1] : void 0
200
+ }, i);
201
+ } catch (e) {}
202
+ }
203
+ return results;
204
+ };
205
+ //#endregion
206
+ //#region src/isAbortError.ts
207
+ const isAbortError = (e, signals) => {
208
+ if (!!e && typeof e === "object" && "name" in e && e.name === "AbortError") return true;
209
+ const filtered = (signals ?? []).filter((v) => v !== void 0 && v !== null);
210
+ for (const signal of filtered) {
211
+ if (!signal.aborted) continue;
212
+ if (e === signal.reason) return true;
213
+ }
214
+ return false;
215
+ };
216
+ //#endregion
217
+ export { Monitor, chunk, chunkStr, createInFlightDeduper, ignorePromise, isAbortError, isObjectEmpty, noop, resultify, trySettlePromises, wait };
package/package.json CHANGED
@@ -1,30 +1,19 @@
1
1
  {
2
2
  "name": "@jsnw/common-utils",
3
- "version": "1.0.0",
3
+ "version": "1.2.0",
4
4
  "description": "Lightweight JavaScript/TypeScript utilities with async helpers, array and string operations",
5
- "main": "./dist/cjs/index.js",
6
- "module": "./dist/esm/index.js",
7
- "types": "./dist/types/index.d.ts",
8
5
  "exports": {
9
- ".": {
10
- "import": "./dist/esm/index.js",
11
- "require": "./dist/cjs/index.js",
12
- "types": "./dist/types/index.d.ts"
6
+ "import": {
7
+ "types": "./dist/index.d.mts",
8
+ "default": "./dist/index.mjs"
9
+ },
10
+ "require": {
11
+ "types": "./dist/index.d.cts",
12
+ "default": "./dist/index.cjs"
13
13
  }
14
14
  },
15
- "scripts": {
16
- "clean": "rimraf ./dist",
17
- "build": "npm run clean && npm run build:cjs && npm run build:esm",
18
- "build:cjs": "tsc -p tsconfig.cjs.json",
19
- "build:esm": "tsc -p tsconfig.esm.json",
20
- "test": "jest --passWithNoTests",
21
- "test:watch": "jest --watch",
22
- "test:coverage": "jest --coverage",
23
- "prepublishOnly": "npm run build"
24
- },
25
15
  "files": [
26
- "./dist",
27
- "README.md"
16
+ "dist"
28
17
  ],
29
18
  "repository": {
30
19
  "type": "git",
@@ -49,10 +38,15 @@
49
38
  "homepage": "https://github.com/pvbaliuk/jsn-utils#readme",
50
39
  "devDependencies": {
51
40
  "@types/jest": "^30.0.0",
52
- "jest": "^30.2.0",
53
- "rimraf": "^6.1.0",
54
- "ts-jest": "^29.4.5",
55
- "tslib": "^2.8.1",
41
+ "jest": "^30.4.2",
42
+ "ts-jest": "^29.4.11",
43
+ "tsdown": "^0.22.7",
56
44
  "typescript": "^5.9.3"
45
+ },
46
+ "scripts": {
47
+ "build": "tsdown",
48
+ "test": "jest --passWithNoTests",
49
+ "test:watch": "jest --watch",
50
+ "test:coverage": "jest --coverage"
57
51
  }
58
- }
52
+ }
package/dist/cjs/chunk.js DELETED
@@ -1,19 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.chunk = void 0;
4
- /**
5
- * Splits an array into smaller arrays of a specified size.
6
- *
7
- * @template T
8
- * @param {T[]} arr - The array to be split into chunks.
9
- * @param {number} chunk_size - The size of each chunk.
10
- * @returns {T[][]} An array containing the chunks.
11
- */
12
- const chunk = (arr, chunk_size) => {
13
- if (chunk_size <= 0)
14
- throw new TypeError('Chunk size should be greater than 0');
15
- return Array.from({
16
- length: Math.ceil(arr.length / chunk_size)
17
- }, (_, i) => arr.slice(i * chunk_size, i * chunk_size + chunk_size));
18
- };
19
- exports.chunk = chunk;
@@ -1,17 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.chunkStr = chunkStr;
4
- /**
5
- * Splits a string into chunks of a specified size
6
- *
7
- * @param {string} str - The string to be split into chunks
8
- * @param {number} chunkSize - The size of each chunk
9
- * @returns {string[]} An array containing the chunks
10
- */
11
- function chunkStr(str, chunkSize) {
12
- if (chunkSize <= 0)
13
- throw new TypeError('Chunk size should be greater than 0');
14
- return Array.from({
15
- length: Math.ceil(str.length / chunkSize)
16
- }, (_, i) => str.slice(i * chunkSize, i * chunkSize + chunkSize));
17
- }
@@ -1,24 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.createInFlightDeduper = createInFlightDeduper;
4
- /**
5
- * Creates a deduplicator for in-flight promises or sync functions.
6
- * Prevents duplicate executions for the same key while a promise is pending.
7
- * Clears the entry after settlement.
8
- * @returns {InFlightDeduper}
9
- */
10
- function createInFlightDeduper() {
11
- const __promises = new Map();
12
- function use(key, fn) {
13
- let promise = __promises.get(key);
14
- if (promise)
15
- return promise;
16
- promise = Promise.resolve(fn())
17
- .finally(() => { __promises.delete(key); });
18
- __promises.set(key, promise);
19
- return promise;
20
- }
21
- return {
22
- use: use
23
- };
24
- }
@@ -1,15 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.ignorePromise = void 0;
4
- const noop_1 = require("./noop");
5
- /**
6
- * Accepts a promise and ensures that its resolution or rejection is ignored.
7
- *
8
- * @param {Promise<any>} promise - The promise to be ignored.
9
- */
10
- const ignorePromise = (promise) => {
11
- promise
12
- .then(noop_1.noop)
13
- .catch(noop_1.noop);
14
- };
15
- exports.ignorePromise = ignorePromise;
package/dist/cjs/index.js DELETED
@@ -1,25 +0,0 @@
1
- "use strict";
2
- var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
- if (k2 === undefined) k2 = k;
4
- var desc = Object.getOwnPropertyDescriptor(m, k);
5
- if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
- desc = { enumerable: true, get: function() { return m[k]; } };
7
- }
8
- Object.defineProperty(o, k2, desc);
9
- }) : (function(o, m, k, k2) {
10
- if (k2 === undefined) k2 = k;
11
- o[k2] = m[k];
12
- }));
13
- var __exportStar = (this && this.__exportStar) || function(m, exports) {
14
- for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
15
- };
16
- Object.defineProperty(exports, "__esModule", { value: true });
17
- __exportStar(require("./noop"), exports);
18
- __exportStar(require("./ignorePromise"), exports);
19
- __exportStar(require("./chunk"), exports);
20
- __exportStar(require("./chunkStr"), exports);
21
- __exportStar(require("./wait"), exports);
22
- __exportStar(require("./isObjectEmpty"), exports);
23
- __exportStar(require("./createInFlightDeduper"), exports);
24
- __exportStar(require("./resultify"), exports);
25
- __exportStar(require("./monitor"), exports);
@@ -1,16 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.isObjectEmpty = isObjectEmpty;
4
- /**
5
- * @param {object} obj
6
- * @returns {boolean}
7
- */
8
- function isObjectEmpty(obj) {
9
- if (Array.isArray(obj))
10
- return obj.length === 0;
11
- for (const key in obj) {
12
- if (Object.prototype.hasOwnProperty.call(obj, key))
13
- return false;
14
- }
15
- return true;
16
- }
@@ -1,75 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.Monitor = void 0;
4
- class Monitor {
5
- marks = new Map();
6
- /**
7
- * @template {(...args: any[]) => any} F
8
- * @param {F} fn
9
- * @returns {ReturnType<F> extends Promise<any> ? Promise<number> : number}
10
- */
11
- static measureFunctionTime(fn) {
12
- const timeStart = Date.now();
13
- const promiseOrResult = fn();
14
- if (promiseOrResult instanceof Promise)
15
- return Promise.resolve(promiseOrResult)
16
- .then(() => Date.now() - timeStart);
17
- return (Date.now() - timeStart);
18
- }
19
- /**
20
- * @param {string} label
21
- * @returns {Monitor}
22
- */
23
- static autoStart(label) {
24
- const instance = new Monitor();
25
- instance.start(label);
26
- return instance;
27
- }
28
- constructor() { }
29
- /**
30
- * @param {string} label
31
- */
32
- start(label) {
33
- if (!this.marks.has(label)) {
34
- this.marks.set(label, [[Date.now()]]);
35
- }
36
- else {
37
- return;
38
- }
39
- }
40
- /**
41
- * @param {string} label
42
- * @param {string} [description]
43
- */
44
- mark(label, description) {
45
- if (!this.marks.has(label))
46
- throw new TypeError(`Label ${label} not found`);
47
- this.marks.get(label).push([Date.now(), description]);
48
- }
49
- /**
50
- * @param {string} label
51
- * @returns {MonitorResult}
52
- */
53
- stop(label) {
54
- const endTime = Date.now();
55
- const marks = this.marks.get(label);
56
- if (!marks)
57
- throw new TypeError(`Label ${label} not found`);
58
- const [firstTs] = marks[0], processedMarks = [];
59
- for (let i = 1; i < marks.length; i++) {
60
- processedMarks.push({
61
- ts: marks[i][0],
62
- diff: marks[i][0] - firstTs,
63
- description: marks[i][1]
64
- });
65
- }
66
- this.marks.delete(label);
67
- return {
68
- marks: processedMarks,
69
- startTs: firstTs,
70
- stopTs: endTime,
71
- totalTime: endTime - firstTs
72
- };
73
- }
74
- }
75
- exports.Monitor = Monitor;
package/dist/cjs/noop.js DELETED
@@ -1,12 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.noop = void 0;
4
- /**
5
- * A no-operation function that performs no action.
6
- * This function can be used as a placeholder or default value
7
- * where a function is required but no operation is necessary.
8
- *
9
- * @returns {void}
10
- */
11
- const noop = () => { };
12
- exports.noop = noop;
@@ -1,23 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.resultify = resultify;
4
- /**
5
- * Executes a function and returns its result as a tuple `[value, error]`.
6
- * Works with both sync and async functions. Never throws.
7
- *
8
- * @template {() => any} F
9
- * @template {Error} E
10
- * @param {F} fn
11
- */
12
- function resultify(fn) {
13
- try {
14
- const promiseOrResult = fn();
15
- if (promiseOrResult instanceof Promise) {
16
- return promiseOrResult.then(res => [res, null]).catch(err => [null, err]);
17
- }
18
- return [promiseOrResult, null];
19
- }
20
- catch (e) {
21
- return [null, e];
22
- }
23
- }
package/dist/cjs/wait.js DELETED
@@ -1,34 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.wait = void 0;
4
- /**
5
- * Waits asynchronously for the specified amount of milliseconds before resolving.
6
- *
7
- * @param {number} wait_ms - The number of milliseconds to wait. If less than 1, the promise resolves immediately.
8
- * @param {AbortSignal} [signal]
9
- * @returns {Promise<void>} A promise that resolves after the specified wait time.
10
- */
11
- const wait = (wait_ms, signal) => {
12
- if (wait_ms < 1)
13
- return Promise.resolve();
14
- if (!Number.isFinite(wait_ms) && !signal)
15
- throw new TypeError('Invalid wait_ms: must be a finite number (or you should provide an AbortSignal as a second argument)');
16
- if (signal?.aborted)
17
- return Promise.resolve();
18
- if (!signal)
19
- return new Promise(resolve => setTimeout(resolve, wait_ms));
20
- return new Promise(resolve => {
21
- let timer_ref = null;
22
- const on_abort = () => {
23
- if (timer_ref)
24
- clearTimeout(timer_ref);
25
- resolve();
26
- };
27
- signal.addEventListener('abort', on_abort, { once: true });
28
- timer_ref = setTimeout(() => {
29
- signal.removeEventListener('abort', on_abort);
30
- resolve();
31
- }, wait_ms);
32
- });
33
- };
34
- exports.wait = wait;
package/dist/esm/chunk.js DELETED
@@ -1,15 +0,0 @@
1
- /**
2
- * Splits an array into smaller arrays of a specified size.
3
- *
4
- * @template T
5
- * @param {T[]} arr - The array to be split into chunks.
6
- * @param {number} chunk_size - The size of each chunk.
7
- * @returns {T[][]} An array containing the chunks.
8
- */
9
- export const chunk = (arr, chunk_size) => {
10
- if (chunk_size <= 0)
11
- throw new TypeError('Chunk size should be greater than 0');
12
- return Array.from({
13
- length: Math.ceil(arr.length / chunk_size)
14
- }, (_, i) => arr.slice(i * chunk_size, i * chunk_size + chunk_size));
15
- };
@@ -1,14 +0,0 @@
1
- /**
2
- * Splits a string into chunks of a specified size
3
- *
4
- * @param {string} str - The string to be split into chunks
5
- * @param {number} chunkSize - The size of each chunk
6
- * @returns {string[]} An array containing the chunks
7
- */
8
- export function chunkStr(str, chunkSize) {
9
- if (chunkSize <= 0)
10
- throw new TypeError('Chunk size should be greater than 0');
11
- return Array.from({
12
- length: Math.ceil(str.length / chunkSize)
13
- }, (_, i) => str.slice(i * chunkSize, i * chunkSize + chunkSize));
14
- }
@@ -1,21 +0,0 @@
1
- /**
2
- * Creates a deduplicator for in-flight promises or sync functions.
3
- * Prevents duplicate executions for the same key while a promise is pending.
4
- * Clears the entry after settlement.
5
- * @returns {InFlightDeduper}
6
- */
7
- export function createInFlightDeduper() {
8
- const __promises = new Map();
9
- function use(key, fn) {
10
- let promise = __promises.get(key);
11
- if (promise)
12
- return promise;
13
- promise = Promise.resolve(fn())
14
- .finally(() => { __promises.delete(key); });
15
- __promises.set(key, promise);
16
- return promise;
17
- }
18
- return {
19
- use: use
20
- };
21
- }
@@ -1,11 +0,0 @@
1
- import { noop } from './noop';
2
- /**
3
- * Accepts a promise and ensures that its resolution or rejection is ignored.
4
- *
5
- * @param {Promise<any>} promise - The promise to be ignored.
6
- */
7
- export const ignorePromise = (promise) => {
8
- promise
9
- .then(noop)
10
- .catch(noop);
11
- };
package/dist/esm/index.js DELETED
@@ -1,9 +0,0 @@
1
- export * from './noop';
2
- export * from './ignorePromise';
3
- export * from './chunk';
4
- export * from './chunkStr';
5
- export * from './wait';
6
- export * from './isObjectEmpty';
7
- export * from './createInFlightDeduper';
8
- export * from './resultify';
9
- export * from './monitor';
@@ -1,13 +0,0 @@
1
- /**
2
- * @param {object} obj
3
- * @returns {boolean}
4
- */
5
- export function isObjectEmpty(obj) {
6
- if (Array.isArray(obj))
7
- return obj.length === 0;
8
- for (const key in obj) {
9
- if (Object.prototype.hasOwnProperty.call(obj, key))
10
- return false;
11
- }
12
- return true;
13
- }