@dvirus-js/utils 1.0.1

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/CHANGELOG.md ADDED
@@ -0,0 +1,3 @@
1
+ # 1.0.0 (2026-02-17)
2
+
3
+ This was a version bump only for utils to align it with other projects, there were no code changes.
package/README.md ADDED
@@ -0,0 +1,99 @@
1
+ # Utils Library
2
+
3
+ This package provides a collection of utility functions for string manipulation, data transformation, async handling, HTTP requests, and more. It is designed to be a shared resource for other packages in the monorepo.
4
+
5
+ ## Available Utilities
6
+
7
+ ### `convert-cases.ts`
8
+ Convert strings between various case formats (camelCase, PascalCase, snake_case, kebab-case, etc.) and normalize strings.
9
+
10
+ ```typescript
11
+ import { convertCase, normalizeString } from './lib/convert-cases';
12
+
13
+ const input = 'HelloWorld_example-string';
14
+ console.log(normalizeString(input)); // 'hello world example string'
15
+ console.log(convertCase(input, 'snake_case')); // 'hello_world_example_string'
16
+ console.log(convertCase(input, 'camelCase')); // 'helloWorldExampleString'
17
+ ```
18
+
19
+ ### `tryCatch.ts`
20
+ Async error handling for promises, returning a tuple of [result, error].
21
+
22
+ ```typescript
23
+ import { tryCatch } from './lib/tryCatch';
24
+
25
+ const [data, error] = await tryCatch(fetch('/api/data'));
26
+ if (error) {
27
+ // handle error
28
+ }
29
+ ```
30
+
31
+ ### `http.ts`
32
+ Simple HTTP client for GET, POST, PUT, PATCH, DELETE requests using fetch.
33
+
34
+ ```typescript
35
+ import { http } from './lib/http';
36
+
37
+ const data = await http.get('/api/data');
38
+ const created = await http.post('/api/data', { name: 'test' });
39
+ ```
40
+
41
+ ### `group-by.ts`
42
+ Group array items by a key.
43
+
44
+ ```typescript
45
+ import { groupBy } from './lib/group-by';
46
+
47
+ const arr = [ { type: 'a', v: 1 }, { type: 'b', v: 2 }, { type: 'a', v: 3 } ];
48
+ const grouped = groupBy(arr, x => x.type);
49
+ // { a: [{type:'a',v:1},{type:'a',v:3}], b: [{type:'b',v:2}] }
50
+ ```
51
+
52
+ ### `delay.ts`
53
+ Delay execution, clamp values, and debounce functions.
54
+
55
+ ```typescript
56
+ import { delay, clamp, debounce } from './lib/delay';
57
+
58
+ await delay(500); // waits 500ms
59
+ const clamped = clamp(0, 10, 5); // 5
60
+ const debounced = debounce(() => console.log('run'), 300);
61
+ debounced();
62
+ ```
63
+
64
+ ### `getProp.ts`
65
+ Get a deeply nested property from an object using a string path, with type safety.
66
+
67
+ ```typescript
68
+ import { getProp } from './lib/getProp';
69
+
70
+ const obj = { a: { b: { c: 42 } } };
71
+ const value = getProp(obj, 'a.b.c'); // 42
72
+ ```
73
+
74
+ ### `Result.ts`
75
+ A Result type for functional error handling (ok/err pattern).
76
+
77
+ ```typescript
78
+ import { Result } from './lib/Result';
79
+
80
+ const res = Result.func(() => JSON.parse('{bad json}'));
81
+ if (res.isErr()) {
82
+ console.error(res.error);
83
+ }
84
+ ```
85
+
86
+ ### `toObject.ts`
87
+ Convert an array to an object by key, or ensure a value is always an array.
88
+
89
+ ```typescript
90
+ import { toObject, toArray } from './lib/toObject';
91
+
92
+ const arr = [{ id: 1 }, { id: 2 }];
93
+ const obj = toObject(arr, x => x.id); // { '1': {id:1}, '2': {id:2} }
94
+ const arr2 = toArray('foo'); // ['foo']
95
+ ```
96
+
97
+ ---
98
+
99
+ This library was generated with [Nx](https://nx.dev).
package/index.d.ts ADDED
@@ -0,0 +1,8 @@
1
+ export * from './lib/convert-cases';
2
+ export * from './lib/tryCatch';
3
+ export * from './lib/http';
4
+ export * from './lib/group-by';
5
+ export * from './lib/delay';
6
+ export * from './lib/getProp';
7
+ export * from './lib/Result';
8
+ export * from './lib/toObject';
package/index.js ADDED
@@ -0,0 +1,326 @@
1
+ function u(t) {
2
+ return t.replace(/([a-z0-9])([A-Z])/g, "$1 $2").replace(/([A-Z]+)([A-Z][a-z])/g, "$1 $2").toLowerCase().replace(/[_-]+/g, " ").replace(/\s+/g, " ").trim();
3
+ }
4
+ function l(t, e) {
5
+ const r = u(t);
6
+ switch (e) {
7
+ case "lowercase":
8
+ return r.toLowerCase();
9
+ case "UPPERCASE":
10
+ return r.toUpperCase();
11
+ case "Title Case":
12
+ return r.split(" ").map(
13
+ (n) => n.charAt(0).toUpperCase() + n.slice(1).toLowerCase()
14
+ ).join(" ");
15
+ case "kebab-case":
16
+ return r.replace(/\s+/g, "-");
17
+ case "snake_case":
18
+ return r.replace(/\s+/g, "_");
19
+ case "camelCase": {
20
+ const n = r.split(" ");
21
+ return n.length === 0 ? "" : n[0].toLowerCase() + n.slice(1).map(
22
+ (s) => s.charAt(0).toUpperCase() + s.slice(1).toLowerCase()
23
+ ).join("");
24
+ }
25
+ case "PascalCase":
26
+ return r.split(" ").map(
27
+ (n) => n.charAt(0).toUpperCase() + n.slice(1).toLowerCase()
28
+ ).join("");
29
+ case "dot.case":
30
+ return r.replace(/\s+/g, ".");
31
+ case "path/case":
32
+ return r.replace(/\s+/g, "/");
33
+ case "Sentence case":
34
+ return r.replace(/(^\s*\w|[.!?]\s*\w)/g, (n) => n.toUpperCase()).replace(/\bi\b/g, "I");
35
+ case "Header-Case":
36
+ return r.split(" ").map(
37
+ (n) => n.charAt(0).toUpperCase() + n.slice(1).toLowerCase()
38
+ ).join("-");
39
+ case "reverse":
40
+ return r.split("").reverse().join("");
41
+ default:
42
+ throw new Error(`Unsupported case type: ${e}`);
43
+ }
44
+ }
45
+ async function p(t) {
46
+ try {
47
+ return [await t, null];
48
+ } catch (e) {
49
+ return [null, e];
50
+ }
51
+ }
52
+ const h = {
53
+ /**
54
+ * Makes a GET request to the specified URL.
55
+ *
56
+ * @param {string} url - The URL to send the GET request to.
57
+ * @param {RequestInit} [options] - Optional request options.
58
+ * @returns {Promise<any>} The response data.
59
+ * @throws {Error} If the response is not ok.
60
+ */
61
+ get: async function(t, e) {
62
+ const r = await fetch(t, e);
63
+ return await o(r);
64
+ },
65
+ /**
66
+ * Makes a POST request to the specified URL with the given data.
67
+ *
68
+ * @template R
69
+ * @param {string} url - The URL to send the POST request to.
70
+ * @param {unknown} data - The data to send in the request body.
71
+ * @param {RequestInit} [options] - Optional request options.
72
+ * @returns {Promise<R>} The response data.
73
+ * @throws {Error} If the response is not ok.
74
+ */
75
+ post: async function(t, e, r) {
76
+ const n = await fetch(t, {
77
+ method: "POST",
78
+ headers: {
79
+ "Content-Type": "application/json",
80
+ ...r?.headers
81
+ },
82
+ body: JSON.stringify(e),
83
+ ...r
84
+ });
85
+ return await o(n);
86
+ },
87
+ /**
88
+ * Makes a DELETE request to the specified URL with the given ID.
89
+ *
90
+ * @template R
91
+ * @param {string} url - The URL to send the DELETE request to.
92
+ * @param {string} id - The ID to send in the request body.
93
+ * @param {RequestInit} [options] - Optional request options.
94
+ * @returns {Promise<R>} The response data.
95
+ * @throws {Error} If the response is not ok.
96
+ */
97
+ delete: async function(t, e, r) {
98
+ const n = await fetch(t, {
99
+ method: "DELETE",
100
+ headers: {
101
+ "Content-Type": "application/json",
102
+ ...r?.headers
103
+ },
104
+ body: JSON.stringify({ id: e }),
105
+ ...r
106
+ });
107
+ return await o(n);
108
+ },
109
+ /**
110
+ * Makes a PATCH request to the specified URL with the given data.
111
+ *
112
+ * @template R
113
+ * @param {string} url - The URL to send the PATCH request to.
114
+ * @param {unknown} data - The data to send in the request body.
115
+ * @param {RequestInit} [options] - Optional request options.
116
+ * @returns {Promise<R>} The response data.
117
+ * @throws {Error} If the response is not ok.
118
+ */
119
+ patch: async function(t, e, r) {
120
+ const n = await fetch(t, {
121
+ method: "PATCH",
122
+ headers: {
123
+ "Content-Type": "application/json",
124
+ ...r?.headers
125
+ },
126
+ body: JSON.stringify(e),
127
+ ...r
128
+ });
129
+ return await o(n);
130
+ },
131
+ /**
132
+ * Makes a PUT request to the specified URL with the given data.
133
+ *
134
+ * @template R
135
+ * @param {string} url - The URL to send the PUT request to.
136
+ * @param {unknown} data - The data to send in the request body.
137
+ * @param {RequestInit} [options] - Optional request options.
138
+ * @returns {Promise<R>} The response data.
139
+ * @throws {Error} If the response is not ok.
140
+ */
141
+ put: async function(t, e, r) {
142
+ const n = await fetch(t, {
143
+ method: "PUT",
144
+ headers: {
145
+ "Content-Type": "application/json",
146
+ ...r?.headers
147
+ },
148
+ body: JSON.stringify(e),
149
+ ...r
150
+ });
151
+ return await o(n);
152
+ }
153
+ };
154
+ async function o(t) {
155
+ if (!t.ok) throw new Error(`Error: ${t.statusText}`);
156
+ return await t.json();
157
+ }
158
+ function f(t, e) {
159
+ const r = {};
160
+ return t?.forEach((n, s) => {
161
+ const a = e(n, s, t);
162
+ a && (r[a] ??= [], r[a].push(n));
163
+ }), r;
164
+ }
165
+ async function w(t) {
166
+ return await new Promise((e) => setTimeout(e, t));
167
+ }
168
+ function d(t, e, r) {
169
+ return e < t ? t : e > r ? r : e;
170
+ }
171
+ function y(t, e) {
172
+ let r;
173
+ return (...n) => {
174
+ clearTimeout(r), r = setTimeout(() => t(...n), e);
175
+ };
176
+ }
177
+ function g(t, e) {
178
+ if (!e || typeof e != "string" || typeof t != "object" || t === null)
179
+ return;
180
+ const r = e.split(".");
181
+ function n(s, a) {
182
+ if (!a || typeof a != "object")
183
+ return;
184
+ const c = s[0];
185
+ if (c in a)
186
+ return s.length === 1 ? a[c] : n(s.slice(1), a[c]);
187
+ }
188
+ return n(r, t);
189
+ }
190
+ class i {
191
+ #e = null;
192
+ #r = null;
193
+ /**
194
+ * Creates a successful result.
195
+ * @param {T} val - The success value.
196
+ * @returns {Result<T, never>} A Result instance representing a success.
197
+ */
198
+ static ok(e) {
199
+ return new i(e, null);
200
+ }
201
+ /**
202
+ * Creates a failed result.
203
+ * @param {E | string} err - The error value or message.
204
+ * @returns {Result<never, E>} A Result instance representing a failure.
205
+ */
206
+ static err(e) {
207
+ return typeof e == "string" ? new i(null, new Error(e)) : new i(null, e);
208
+ }
209
+ /**
210
+ * Wraps a promise in a Result.
211
+ * @param {Promise<T>} promise - The promise to wrap.
212
+ * @returns {Promise<Result<T, E>>} A promise that resolves to a Result.
213
+ */
214
+ static async promise(e) {
215
+ return e.then((r) => i.ok(r ?? "void")).catch((r) => i.err(r));
216
+ }
217
+ /**
218
+ * Wraps a function call in a Result.
219
+ * @param {(...args: any[]) => T} func - The function to call.
220
+ * @param {...any[]} args - The arguments to pass to the function.
221
+ * @returns {Result<T, E>} A Result instance representing the function call result.
222
+ */
223
+ static func(e, ...r) {
224
+ try {
225
+ const n = e(...r);
226
+ return i.ok(n);
227
+ } catch (n) {
228
+ return i.err(n);
229
+ }
230
+ }
231
+ /**
232
+ * @param {T | null} ok - The success value.
233
+ * @param {E | null} err - The error value.
234
+ * @throws {Error} If both ok and err are provided or neither is provided.
235
+ */
236
+ constructor(e, r) {
237
+ if (!e && !r)
238
+ throw new Error("Result must be initialized with either an ok or an err value");
239
+ if (e && r)
240
+ throw new Error("Result can't be initialized with both an ok and an err value");
241
+ e != null ? this.#e = e : this.#r = r;
242
+ }
243
+ /**
244
+ * Gets the success value, throwing an error if the result is a failure.
245
+ * @returns {T} The success value.
246
+ * @throws {Error} If the result is a failure.
247
+ */
248
+ get value() {
249
+ return this.expect("add error handling");
250
+ }
251
+ /**
252
+ * Unwraps the result, returning the success value or throwing the error.
253
+ * @returns {T} The success value.
254
+ * @throws {E} If the result is a failure.
255
+ */
256
+ unwrap() {
257
+ if (this.isOk())
258
+ return this.#e;
259
+ throw this.isErr() ? this.#r : new Error("Unknown error");
260
+ }
261
+ /**
262
+ * Unwraps the result, returning the success value or a default value if the result is a failure.
263
+ * @param {T} defaultValue - The default value to return if the result is a failure.
264
+ * @returns {T} The success value or the default value.
265
+ */
266
+ unwrapOr(e) {
267
+ return this.isOk() ? this.#e : e;
268
+ }
269
+ /**
270
+ * Gets the success value, throwing a custom error message if the result is a failure.
271
+ * @param {string} msg - The custom error message.
272
+ * @returns {T} The success value.
273
+ * @throws {Error} If the result is a failure.
274
+ */
275
+ expect(e) {
276
+ if (this.isOk())
277
+ return this.#e;
278
+ if (this.isErr()) {
279
+ const r = this.#r;
280
+ throw new Error(e + `:
281
+ ` + r.message);
282
+ }
283
+ throw new Error(e);
284
+ }
285
+ /**
286
+ * Checks if the result is a success.
287
+ * @returns {boolean} True if the result is a success, false otherwise.
288
+ */
289
+ isOk() {
290
+ return this.#e != null;
291
+ }
292
+ /**
293
+ * Checks if the result is a failure.
294
+ * @returns {boolean} True if the result is a failure, false otherwise.
295
+ */
296
+ isErr() {
297
+ return this.#r != null;
298
+ }
299
+ /**
300
+ * Gets the error value.
301
+ * @returns {E | null} The error value, or null if the result is a success.
302
+ */
303
+ get error() {
304
+ return this.#r;
305
+ }
306
+ }
307
+ function C(t, e) {
308
+ return t.reduce((r, n) => (r[e(n).toString()] = n, r), {});
309
+ }
310
+ function E(t, e = []) {
311
+ return t == null ? e : Array.isArray(t) ? t : [t];
312
+ }
313
+ export {
314
+ i as Result,
315
+ d as clamp,
316
+ l as convertCase,
317
+ y as debounce,
318
+ w as delay,
319
+ g as getProp,
320
+ f as groupBy,
321
+ h as http,
322
+ u as normalizeString,
323
+ E as toArray,
324
+ C as toObject,
325
+ p as tryCatch
326
+ };
@@ -0,0 +1,79 @@
1
+ /**
2
+ * A class representing a result of an operation that can either be a success (ok) or a failure (err).
3
+ * @template T - The type of the success value.
4
+ * @template E - The type of the error value, extending Error.
5
+ */
6
+ export declare class Result<T, E extends Error = Error> {
7
+ #private;
8
+ /**
9
+ * Creates a successful result.
10
+ * @param {T} val - The success value.
11
+ * @returns {Result<T, never>} A Result instance representing a success.
12
+ */
13
+ static ok<T>(val: T): Result<T, never>;
14
+ /**
15
+ * Creates a failed result.
16
+ * @param {E | string} err - The error value or message.
17
+ * @returns {Result<never, E>} A Result instance representing a failure.
18
+ */
19
+ static err<E extends Error>(err: E | string): Result<never, E>;
20
+ /**
21
+ * Wraps a promise in a Result.
22
+ * @param {Promise<T>} promise - The promise to wrap.
23
+ * @returns {Promise<Result<T, E>>} A promise that resolves to a Result.
24
+ */
25
+ static promise<T, E extends Error = Error>(promise: Promise<T>): Promise<Result<T, E>>;
26
+ /**
27
+ * Wraps a function call in a Result.
28
+ * @param {(...args: any[]) => T} func - The function to call.
29
+ * @param {...any[]} args - The arguments to pass to the function.
30
+ * @returns {Result<T, E>} A Result instance representing the function call result.
31
+ */
32
+ static func<T, E extends Error = Error, TParam extends Array<unknown> = []>(func: (...args: TParam) => T, ...args: TParam): Result<T, E>;
33
+ /**
34
+ * @param {T | null} ok - The success value.
35
+ * @param {E | null} err - The error value.
36
+ * @throws {Error} If both ok and err are provided or neither is provided.
37
+ */
38
+ constructor(ok: T | null, err: E | null);
39
+ /**
40
+ * Gets the success value, throwing an error if the result is a failure.
41
+ * @returns {T} The success value.
42
+ * @throws {Error} If the result is a failure.
43
+ */
44
+ get value(): T;
45
+ /**
46
+ * Unwraps the result, returning the success value or throwing the error.
47
+ * @returns {T} The success value.
48
+ * @throws {E} If the result is a failure.
49
+ */
50
+ unwrap(): T;
51
+ /**
52
+ * Unwraps the result, returning the success value or a default value if the result is a failure.
53
+ * @param {T} defaultValue - The default value to return if the result is a failure.
54
+ * @returns {T} The success value or the default value.
55
+ */
56
+ unwrapOr(defaultValue: T): T;
57
+ /**
58
+ * Gets the success value, throwing a custom error message if the result is a failure.
59
+ * @param {string} msg - The custom error message.
60
+ * @returns {T} The success value.
61
+ * @throws {Error} If the result is a failure.
62
+ */
63
+ expect(msg: string): T;
64
+ /**
65
+ * Checks if the result is a success.
66
+ * @returns {boolean} True if the result is a success, false otherwise.
67
+ */
68
+ isOk(): this is Result<T, never>;
69
+ /**
70
+ * Checks if the result is a failure.
71
+ * @returns {boolean} True if the result is a failure, false otherwise.
72
+ */
73
+ isErr(): this is Result<never, E>;
74
+ /**
75
+ * Gets the error value.
76
+ * @returns {E | null} The error value, or null if the result is a success.
77
+ */
78
+ get error(): this extends Result<never, E> ? E : E | null;
79
+ }
@@ -0,0 +1,15 @@
1
+ /**
2
+ * Normalizes any string to lowercase with spaces
3
+ * Handles various cases like special characters, extra spaces, and different formats
4
+ * @param input - The string to normalize
5
+ * @returns A normalized string in lowercase with single spaces
6
+ */
7
+ export declare function normalizeString(input: string): string;
8
+ /**
9
+ * Converts a string to various cases
10
+ * @param input - The string to convert
11
+ * @param caseType - The target case type
12
+ * @returns The string converted to the specified case
13
+ */
14
+ export type CaseType = 'lowercase' | 'UPPERCASE' | 'Title Case' | 'kebab-case' | 'snake_case' | 'camelCase' | 'PascalCase' | 'dot.case' | 'path/case' | 'Sentence case' | 'Header-Case' | 'reverse';
15
+ export declare function convertCase(input: string, caseType: CaseType): string;
package/lib/delay.d.ts ADDED
@@ -0,0 +1,21 @@
1
+ /**
2
+ * Delay for a given time
3
+ * @param ms - Time in milliseconds
4
+ * @returns Promise
5
+ */
6
+ export declare function delay(ms: number): Promise<unknown>;
7
+ /**
8
+ * Clamp a value between a minimum and maximum value
9
+ * @param min - Minimum value
10
+ * @param value - Value
11
+ * @param max - Maximum value
12
+ * @returns Clamped value
13
+ */
14
+ export declare function clamp(min: number, value: number, max: number): number;
15
+ /**
16
+ * Debounce a function
17
+ * @param func - Function to debounce
18
+ * @param delay - Delay in milliseconds
19
+ * @returns Debounced function
20
+ */
21
+ export declare function debounce<T extends (...args: any[]) => void>(func: T, delay: number): (...args: Parameters<T>) => void;
@@ -0,0 +1,17 @@
1
+ /**
2
+ * A utility type to get the value type at a given path in an object.
3
+ *
4
+ * @template T - The type of the object.
5
+ * @template P - The path as a string.
6
+ */
7
+ export type PathValue<T, P extends string> = P extends `${infer K}.${infer Rest}` ? K extends keyof T ? PathValue<T[K], Rest> : undefined : P extends keyof T ? T[P] : undefined;
8
+ /**
9
+ * Retrieves the value at a given path in an object.
10
+ *
11
+ * @template T - The type of the object.
12
+ * @template P - The path as a string.
13
+ * @param {T} obj - The object to retrieve the value from.
14
+ * @param {P} path - The path to the value in the object.
15
+ * @returns {PathValue<T, P>} The value at the given path, or undefined if the path is invalid.
16
+ */
17
+ export declare function getProp<T, P extends string>(obj: T, path: P): PathValue<T, P>;
@@ -0,0 +1,11 @@
1
+ /**
2
+ * Groups the elements of an array based on the provided keyGetter function.
3
+ *
4
+ * @param value - The array to group.
5
+ * @param {function(item T, number, array T[]): string | number} keyGetter - A function that takes an element, its
6
+ * index, and
7
+ * the array, and returns a key to group by.
8
+ * @returns {Record<string, array T>} - An object where the keys are the results of the keyGetter function and the
9
+ * values are arrays of elements that correspond to those keys.
10
+ */
11
+ export declare function groupBy<T>(value: T[], keyGetter: (item: T, index: number, array: T[]) => string | number): Record<string, T[]>;
package/lib/http.d.ts ADDED
@@ -0,0 +1,58 @@
1
+ /**
2
+ * A utility object for making HTTP requests.
3
+ */
4
+ export declare const http: {
5
+ /**
6
+ * Makes a GET request to the specified URL.
7
+ *
8
+ * @param {string} url - The URL to send the GET request to.
9
+ * @param {RequestInit} [options] - Optional request options.
10
+ * @returns {Promise<any>} The response data.
11
+ * @throws {Error} If the response is not ok.
12
+ */
13
+ get: <R = any>(url: string, options?: RequestInit) => Promise<R>;
14
+ /**
15
+ * Makes a POST request to the specified URL with the given data.
16
+ *
17
+ * @template R
18
+ * @param {string} url - The URL to send the POST request to.
19
+ * @param {unknown} data - The data to send in the request body.
20
+ * @param {RequestInit} [options] - Optional request options.
21
+ * @returns {Promise<R>} The response data.
22
+ * @throws {Error} If the response is not ok.
23
+ */
24
+ post: <R = any>(url: string, data: unknown, options?: RequestInit) => Promise<R>;
25
+ /**
26
+ * Makes a DELETE request to the specified URL with the given ID.
27
+ *
28
+ * @template R
29
+ * @param {string} url - The URL to send the DELETE request to.
30
+ * @param {string} id - The ID to send in the request body.
31
+ * @param {RequestInit} [options] - Optional request options.
32
+ * @returns {Promise<R>} The response data.
33
+ * @throws {Error} If the response is not ok.
34
+ */
35
+ delete: <R = any>(url: string, id: string, options?: RequestInit) => Promise<R>;
36
+ /**
37
+ * Makes a PATCH request to the specified URL with the given data.
38
+ *
39
+ * @template R
40
+ * @param {string} url - The URL to send the PATCH request to.
41
+ * @param {unknown} data - The data to send in the request body.
42
+ * @param {RequestInit} [options] - Optional request options.
43
+ * @returns {Promise<R>} The response data.
44
+ * @throws {Error} If the response is not ok.
45
+ */
46
+ patch: <R = any>(url: string, data: unknown, options?: RequestInit) => Promise<R>;
47
+ /**
48
+ * Makes a PUT request to the specified URL with the given data.
49
+ *
50
+ * @template R
51
+ * @param {string} url - The URL to send the PUT request to.
52
+ * @param {unknown} data - The data to send in the request body.
53
+ * @param {RequestInit} [options] - Optional request options.
54
+ * @returns {Promise<R>} The response data.
55
+ * @throws {Error} If the response is not ok.
56
+ */
57
+ put: <R = any>(url: string, data: unknown, options?: RequestInit) => Promise<R>;
58
+ };
@@ -0,0 +1,4 @@
1
+ export declare function toObject<T extends Record<string, any> | string | number>(list: T[], keyGetter: (item: T) => string | number | {
2
+ toString: () => string;
3
+ }): Record<string, T>;
4
+ export declare function toArray<T>(obj: T | T[] | undefined | null, defaultValue?: T[]): T[];
@@ -0,0 +1,14 @@
1
+ /**
2
+ * Types for the result tuple with discriminated union
3
+ * @template T - Type of the successful result
4
+ * @template E - Type of the error, defaults to Error
5
+ */
6
+ export type TryResult<T, E = Error> = [T, null] | [null, E];
7
+ /**
8
+ * Main wrapper function to handle promise with try-catch
9
+ * @template T - Type of the successful result
10
+ * @template E - Type of the error, defaults to Error
11
+ * @param {Promise<T>} promise - The promise to handle
12
+ * @returns {Promise<TryResult<T, E>>} - A promise that resolves to a tuple with either the result or the error
13
+ */
14
+ export declare function tryCatch<T, E = Error>(promise: Promise<T>): Promise<TryResult<T, E>>;
package/package.json ADDED
@@ -0,0 +1,11 @@
1
+ {
2
+ "name": "@dvirus-js/utils",
3
+ "version": "1.0.1",
4
+ "type": "module",
5
+ "main": "./index.js",
6
+ "types": "./index.d.ts",
7
+ "dependencies": {},
8
+ "publishConfig": {
9
+ "access": "public"
10
+ }
11
+ }