@jsnw/common-utils 1.0.0 → 1.1.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/package.json CHANGED
@@ -1,30 +1,19 @@
1
1
  {
2
2
  "name": "@jsnw/common-utils",
3
- "version": "1.0.0",
3
+ "version": "1.1.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
- }
@@ -1,71 +0,0 @@
1
- export class Monitor {
2
- marks = new Map();
3
- /**
4
- * @template {(...args: any[]) => any} F
5
- * @param {F} fn
6
- * @returns {ReturnType<F> extends Promise<any> ? Promise<number> : number}
7
- */
8
- static measureFunctionTime(fn) {
9
- const timeStart = Date.now();
10
- const promiseOrResult = fn();
11
- if (promiseOrResult instanceof Promise)
12
- return Promise.resolve(promiseOrResult)
13
- .then(() => Date.now() - timeStart);
14
- return (Date.now() - timeStart);
15
- }
16
- /**
17
- * @param {string} label
18
- * @returns {Monitor}
19
- */
20
- static autoStart(label) {
21
- const instance = new Monitor();
22
- instance.start(label);
23
- return instance;
24
- }
25
- constructor() { }
26
- /**
27
- * @param {string} label
28
- */
29
- start(label) {
30
- if (!this.marks.has(label)) {
31
- this.marks.set(label, [[Date.now()]]);
32
- }
33
- else {
34
- return;
35
- }
36
- }
37
- /**
38
- * @param {string} label
39
- * @param {string} [description]
40
- */
41
- mark(label, description) {
42
- if (!this.marks.has(label))
43
- throw new TypeError(`Label ${label} not found`);
44
- this.marks.get(label).push([Date.now(), description]);
45
- }
46
- /**
47
- * @param {string} label
48
- * @returns {MonitorResult}
49
- */
50
- stop(label) {
51
- const endTime = Date.now();
52
- const marks = this.marks.get(label);
53
- if (!marks)
54
- throw new TypeError(`Label ${label} not found`);
55
- const [firstTs] = marks[0], processedMarks = [];
56
- for (let i = 1; i < marks.length; i++) {
57
- processedMarks.push({
58
- ts: marks[i][0],
59
- diff: marks[i][0] - firstTs,
60
- description: marks[i][1]
61
- });
62
- }
63
- this.marks.delete(label);
64
- return {
65
- marks: processedMarks,
66
- startTs: firstTs,
67
- stopTs: endTime,
68
- totalTime: endTime - firstTs
69
- };
70
- }
71
- }
package/dist/esm/noop.js DELETED
@@ -1,8 +0,0 @@
1
- /**
2
- * A no-operation function that performs no action.
3
- * This function can be used as a placeholder or default value
4
- * where a function is required but no operation is necessary.
5
- *
6
- * @returns {void}
7
- */
8
- export const noop = () => { };
@@ -1,20 +0,0 @@
1
- /**
2
- * Executes a function and returns its result as a tuple `[value, error]`.
3
- * Works with both sync and async functions. Never throws.
4
- *
5
- * @template {() => any} F
6
- * @template {Error} E
7
- * @param {F} fn
8
- */
9
- export function resultify(fn) {
10
- try {
11
- const promiseOrResult = fn();
12
- if (promiseOrResult instanceof Promise) {
13
- return promiseOrResult.then(res => [res, null]).catch(err => [null, err]);
14
- }
15
- return [promiseOrResult, null];
16
- }
17
- catch (e) {
18
- return [null, e];
19
- }
20
- }
package/dist/esm/wait.js DELETED
@@ -1,30 +0,0 @@
1
- /**
2
- * Waits asynchronously for the specified amount of milliseconds before resolving.
3
- *
4
- * @param {number} wait_ms - The number of milliseconds to wait. If less than 1, the promise resolves immediately.
5
- * @param {AbortSignal} [signal]
6
- * @returns {Promise<void>} A promise that resolves after the specified wait time.
7
- */
8
- export const wait = (wait_ms, signal) => {
9
- if (wait_ms < 1)
10
- return Promise.resolve();
11
- if (!Number.isFinite(wait_ms) && !signal)
12
- throw new TypeError('Invalid wait_ms: must be a finite number (or you should provide an AbortSignal as a second argument)');
13
- if (signal?.aborted)
14
- return Promise.resolve();
15
- if (!signal)
16
- return new Promise(resolve => setTimeout(resolve, wait_ms));
17
- return new Promise(resolve => {
18
- let timer_ref = null;
19
- const on_abort = () => {
20
- if (timer_ref)
21
- clearTimeout(timer_ref);
22
- resolve();
23
- };
24
- signal.addEventListener('abort', on_abort, { once: true });
25
- timer_ref = setTimeout(() => {
26
- signal.removeEventListener('abort', on_abort);
27
- resolve();
28
- }, wait_ms);
29
- });
30
- };
@@ -1,9 +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 declare const chunk: <T extends any>(arr: T[], chunk_size: number) => T[][];
@@ -1,8 +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 declare function chunkStr(str: string, chunkSize: number): string[];
@@ -1,10 +0,0 @@
1
- export type InFlightDeduper = {
2
- use: <F extends () => any>(key: string, fn: F) => Promise<Awaited<ReturnType<F>>>;
3
- };
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
- export declare function createInFlightDeduper(): InFlightDeduper;
@@ -1,6 +0,0 @@
1
- /**
2
- * Accepts a promise and ensures that its resolution or rejection is ignored.
3
- *
4
- * @param {Promise<any>} promise - The promise to be ignored.
5
- */
6
- export declare const ignorePromise: (promise: Promise<any>) => void;
@@ -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,5 +0,0 @@
1
- /**
2
- * @param {object} obj
3
- * @returns {boolean}
4
- */
5
- export declare function isObjectEmpty(obj: object): boolean;
@@ -1,40 +0,0 @@
1
- export type MonitorMark = {
2
- ts: number;
3
- diff: number;
4
- description?: string;
5
- };
6
- export type MonitorResult = {
7
- marks: MonitorMark[];
8
- startTs: number;
9
- stopTs: number;
10
- totalTime: number;
11
- };
12
- export declare class Monitor {
13
- private readonly marks;
14
- /**
15
- * @template {(...args: any[]) => any} F
16
- * @param {F} fn
17
- * @returns {ReturnType<F> extends Promise<any> ? Promise<number> : number}
18
- */
19
- static measureFunctionTime<F extends (...args: any[]) => any>(fn: F): ReturnType<F> extends Promise<any> ? Promise<number> : number;
20
- /**
21
- * @param {string} label
22
- * @returns {Monitor}
23
- */
24
- static autoStart(label: string): Monitor;
25
- constructor();
26
- /**
27
- * @param {string} label
28
- */
29
- start(label: string): void;
30
- /**
31
- * @param {string} label
32
- * @param {string} [description]
33
- */
34
- mark(label: string, description?: string): void;
35
- /**
36
- * @param {string} label
37
- * @returns {MonitorResult}
38
- */
39
- stop(label: string): MonitorResult;
40
- }
@@ -1,8 +0,0 @@
1
- /**
2
- * A no-operation function that performs no action.
3
- * This function can be used as a placeholder or default value
4
- * where a function is required but no operation is necessary.
5
- *
6
- * @returns {void}
7
- */
8
- export declare const noop: () => void;