@germondai/ts-utils 0.0.1 → 0.0.3

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/module.js CHANGED
@@ -1,15 +1,11 @@
1
1
  // src/runtime/collection.ts
2
- var hasDuplicates = (array, keyExtractor) => {
3
- const seen = new Set;
4
- for (const item of array) {
5
- const key = keyExtractor ? keyExtractor(item) : item;
6
- if (seen.has(key))
7
- return true;
8
- seen.add(key);
9
- }
10
- return false;
11
- };
12
- var uniqueArray = (array) => [...new Set(array)];
2
+ var hasDuplicates = (array, keyExtractor) => new Set(array.map((value, index) => keyExtractor?.(value, index, array) || value)).size < array.length;
3
+ var uniqueArray = (array, keyExtractor) => [
4
+ ...new Map(array.map((value, index, array2) => [
5
+ keyExtractor?.(value, index, array2) || value,
6
+ value
7
+ ])).values()
8
+ ];
13
9
  // src/runtime/constants.ts
14
10
  var SUPPORTED_DISPLAYABLE_MEDIA_TYPES = {
15
11
  images: [
@@ -61,14 +57,29 @@ var escapeHTML = (str) => {
61
57
  };
62
58
  return str.replace(/[&<>"']/g, (char) => escapeMap[char] || char);
63
59
  };
60
+ var unescapeHTML = (str) => {
61
+ const unescapeMap = {
62
+ "&amp;": "&",
63
+ "&lt;": "<",
64
+ "&gt;": ">",
65
+ "&quot;": '"',
66
+ "&#039;": "'"
67
+ };
68
+ return str.replace(/&[a-zA-Z0-9#]+;/g, (entity) => unescapeMap[entity] || entity);
69
+ };
64
70
  // src/runtime/data.ts
65
71
  var clone = (data) => JSON.parse(JSON.stringify(data));
66
72
  // src/runtime/errors.ts
67
- var catchError = (promise, errorsToCatch) => promise().then((data) => ({ data, ok: true })).catch((error) => {
68
- if (errorsToCatch === undefined || errorsToCatch.some((e) => error instanceof e))
69
- return { error, ok: false };
70
- throw error;
71
- });
73
+ var catchError = async (promise, errorsToCatch) => {
74
+ try {
75
+ const data = await promise();
76
+ return { data, ok: true };
77
+ } catch (error) {
78
+ if (errorsToCatch === undefined || errorsToCatch.some((e) => error instanceof e))
79
+ return { error, ok: false };
80
+ throw error;
81
+ }
82
+ };
72
83
  // src/runtime/math.ts
73
84
  var rand = (n, m = 0) => Math.floor(Math.random() * (m - n + 1)) + n;
74
85
  var percentage = (value, maxValue, decimalPlaces = 2) => {
@@ -97,14 +108,6 @@ var isCreditCard = (value) => /^(?:4[0-9]{12}(?:[0-9]{3})?|5[1-5][0-9]{14}|6(?:0
97
108
  var isDomain = (value) => /^(?!:\/\/)([a-zA-Z0-9-_]{1,63}\.)+[a-zA-Z]{2,63}$/.test(value);
98
109
  var isPostalCode = (value) => /^[A-Za-z0-9\s-]{3,10}$/.test(value);
99
110
  var isISODate = (value) => /^\d{4}-(0[1-9]|1[0-2])-(0[1-9]|[12]\d|3[01])$/.test(value);
100
- var isJson = (value) => {
101
- try {
102
- JSON.parse(value);
103
- return true;
104
- } catch {
105
- return false;
106
- }
107
- };
108
111
  var isBase64 = (value) => /^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(value);
109
112
  var isSlug = (value) => /^[a-z0-9]+(?:-[a-z0-9]+)*$/.test(value);
110
113
  // src/runtime/size.ts
@@ -118,6 +121,29 @@ var formatBytes = (bytes, decimals = 2) => {
118
121
  const size = parseFloat((bytes / Math.pow(k, i)).toFixed(dm));
119
122
  return `${size} ${sizes[i]}`;
120
123
  };
124
+ var toBytes = (size) => {
125
+ const match = size.trim().match(/^(\d+\.?\d*)\s*(B|KB|MB|GB|TB)$/i);
126
+ if (!match)
127
+ return;
128
+ const value = Number(match[1]);
129
+ const unit = match[2]?.toUpperCase();
130
+ if (isNaN(value) || value < 0)
131
+ return;
132
+ switch (unit) {
133
+ case "B":
134
+ return value;
135
+ case "KB":
136
+ return value * 1024;
137
+ case "MB":
138
+ return value * 1024 * 1024;
139
+ case "GB":
140
+ return value * 1024 * 1024 * 1024;
141
+ case "TB":
142
+ return value * 1024 * 1024 * 1024 * 1024;
143
+ default:
144
+ return;
145
+ }
146
+ };
121
147
  // src/runtime/time.ts
122
148
  var formatTime = (seconds) => {
123
149
  const hours = Math.floor(seconds / 3600);
@@ -144,6 +170,36 @@ var formatDuration = (ms) => {
144
170
  return `${min}m ${sec % 60}s`;
145
171
  return `${sec}s`;
146
172
  };
173
+ var toSeconds = (time) => {
174
+ time = time?.trim();
175
+ if (!time)
176
+ return;
177
+ if (/^\d+$/.test(time)) {
178
+ const seconds2 = Number(time);
179
+ if (isNaN(seconds2))
180
+ return;
181
+ return seconds2;
182
+ }
183
+ if (time.includes(":")) {
184
+ const parts = time.split(":").map(Number);
185
+ if (parts.some(isNaN))
186
+ return;
187
+ if (parts.length === 2)
188
+ return (parts[0] || 0) * 60 + (parts[1] || 0);
189
+ else if (parts.length === 3)
190
+ return (parts[0] || 0) * 3600 + (parts[1] || 0) * 60 + (parts[2] || 0);
191
+ return;
192
+ }
193
+ const match = time.match(/(?:(\d+)h)?\s*(?:(\d+)m)?\s*(?:(\d+)s)?/i);
194
+ if (!match || !match.some((v, i) => i > 0 && v !== undefined))
195
+ return;
196
+ const hours = Number(match[1] || "0");
197
+ const minutes = Number(match[2] || "0");
198
+ const seconds = Number(match[3] || "0");
199
+ if (isNaN(hours) || isNaN(minutes) || isNaN(seconds))
200
+ return;
201
+ return hours * 3600 + minutes * 60 + seconds;
202
+ };
147
203
  // src/runtime/type.ts
148
204
  var isPrimitive = (value) => value === null || value === undefined || typeof value !== "object" && typeof value !== "function";
149
205
  var isObject = (value) => value !== null && typeof value === "object" && value.constructor === Object;
@@ -157,6 +213,16 @@ var isEmpty = (value) => {
157
213
  return Object.keys(value).length === 0;
158
214
  return false;
159
215
  };
216
+ var isJSON = (value) => {
217
+ if (typeof value !== "string")
218
+ return false;
219
+ try {
220
+ JSON.parse(value);
221
+ return true;
222
+ } catch {
223
+ return false;
224
+ }
225
+ };
160
226
  // src/runtime/url.ts
161
227
  var getQueryParams = (urlString) => {
162
228
  const url = new URL(urlString);
@@ -192,15 +258,18 @@ var buildUrl = (baseUrl, path, queryParams) => {
192
258
  export {
193
259
  updateQueryParam,
194
260
  uniqueArray,
261
+ unescapeHTML,
195
262
  truncate,
196
263
  toggleCase,
197
264
  toTitleCase,
198
265
  toSnakeCase,
199
266
  toSentenceCase,
267
+ toSeconds,
200
268
  toPascalCase,
201
269
  toKebabCase,
202
270
  toConstantCase,
203
271
  toCamelCase,
272
+ toBytes,
204
273
  stripTags,
205
274
  slugify,
206
275
  sleep,
@@ -216,7 +285,7 @@ export {
216
285
  isPhoneNumber,
217
286
  isObject,
218
287
  isMacAddress,
219
- isJson,
288
+ isJSON,
220
289
  isISODate,
221
290
  isIPv6,
222
291
  isIPv4,
@@ -1,19 +1,53 @@
1
1
  /**
2
- * Checks if an array contains duplicate values.
2
+ * Determines whether an array contains duplicate values.
3
3
  *
4
4
  * @param array - The array to check for duplicates.
5
+ * @param keyExtractor - Optional function to extract a key for comparison. If provided, duplicates are determined based on the extracted key.
5
6
  * @returns True if the array contains duplicates, false otherwise.
6
7
  *
7
8
  * @example
9
+ * // Basic usage with primitive values
8
10
  * hasDuplicates([1, 2, 3, 4, 1]); // true
9
11
  * hasDuplicates(['a', 'b', 'c']); // false
12
+ *
13
+ * // Usage with objects and a key extractor
10
14
  * hasDuplicates([{ id: 1 }, { id: 2 }, { id: 1 }], (item) => item.id); // true
11
15
  */
12
- export declare const hasDuplicates: <T>(array: T[], keyExtractor?: (item: T) => unknown) => boolean;
16
+ export declare const hasDuplicates: <T>(array: T[], keyExtractor?: (value: T, index: number, array: T[]) => string | number) => boolean;
13
17
  /**
14
- * Removes duplicates from an array.
18
+ * Removes duplicates from an array based on a key function.
15
19
  *
16
20
  * @param array - The array to process.
21
+ * @param keyExtractor - Function to generate a unique key for each item.
17
22
  * @returns A new array without duplicates.
18
23
  */
19
- export declare const uniqueArray: <T>(array: T[]) => T[];
24
+ /**
25
+ * Returns a new array containing only unique elements from the input array.
26
+ * Uniqueness is determined based on the values returned by the `keyExtractor` function,
27
+ * or by the elements themselves if no `keyExtractor` is provided.
28
+ *
29
+ * @typeParam T - The type of elements in the input array.
30
+ * @param array - The input array from which to extract unique elements.
31
+ * @param keyExtractor - An optional function that extracts a key from each element
32
+ * to determine uniqueness. If not provided, the elements themselves are used.
33
+ * The function receives the current element, its index, and the entire array as arguments.
34
+ * @returns A new array containing only unique elements from the input array.
35
+ *
36
+ * @example
37
+ * // Using default behavior (elements themselves determine uniqueness)
38
+ * const numbers = [1, 2, 2, 3, 4, 4];
39
+ * const uniqueNumbers = uniqueArray(numbers);
40
+ * console.log(uniqueNumbers); // Output: [1, 2, 3, 4]
41
+ *
42
+ * @example
43
+ * // Using a keyExtractor to determine uniqueness
44
+ * const users = [
45
+ * { id: 1, name: 'Alice' },
46
+ * { id: 2, name: 'Bob' },
47
+ * { id: 1, name: 'Alice' },
48
+ * ];
49
+ * const uniqueUsers = uniqueArray(users, user => user.id);
50
+ * console.log(uniqueUsers);
51
+ * // Output: [{ id: 1, name: 'Alice' }, { id: 2, name: 'Bob' }]
52
+ */
53
+ export declare const uniqueArray: <T>(array: T[], keyExtractor?: (value: T, index: number, array: T[]) => string | number) => T[];
@@ -104,3 +104,11 @@ export declare const stripTags: (html: string) => string;
104
104
  * @returns The HTML-escaped string.
105
105
  */
106
106
  export declare const escapeHTML: (str: string) => string;
107
+ /**
108
+ * Unescapes HTML entities in a string.
109
+ * Converts HTML entities like `&amp;`, `&lt;`, `&gt;`, `&quot;`, and `&#039;` back to their original characters.
110
+ *
111
+ * @param str - The input string to unescape.
112
+ * @returns The unescaped string.
113
+ */
114
+ export declare const unescapeHTML: (str: string) => string;
@@ -11,7 +11,11 @@
11
11
  * @returns A promise resolving to an object with either the data or an error.
12
12
  */
13
13
  export declare const catchError: <T, E extends new (message?: string) => Error>(promise: () => Promise<T>, errorsToCatch?: E[]) => Promise<{
14
- data?: T;
15
- ok: boolean;
16
- error?: InstanceType<E>;
14
+ data: T;
15
+ ok: true;
16
+ error?: never;
17
+ } | {
18
+ data?: never;
19
+ ok: false;
20
+ error: InstanceType<E>;
17
21
  }>;
@@ -145,17 +145,6 @@ export declare const isPostalCode: (value: string) => boolean;
145
145
  * isISODate('2024-13-01'); // false
146
146
  */
147
147
  export declare const isISODate: (value: string) => boolean;
148
- /**
149
- * Checks if a given string is a valid JSON string.
150
- *
151
- * @param value - The string to validate.
152
- * @returns True if the string is valid JSON, false otherwise.
153
- *
154
- * @example
155
- * isJson('{"name": "John"}'); // true
156
- * isJson('{invalid}'); // false
157
- */
158
- export declare const isJson: (value: string) => boolean;
159
148
  /**
160
149
  * Checks if a given string is a valid Base64-encoded string.
161
150
  *
@@ -8,3 +8,26 @@
8
8
  * @returns A string representing the file size (e.g., "1.23 MB").
9
9
  */
10
10
  export declare const formatBytes: (bytes: number, decimals?: number) => string;
11
+ /**
12
+ * Converts a human-readable size string into its equivalent size in bytes.
13
+ *
14
+ * @param size - The size string to convert. It should be in the format of a number
15
+ * followed by a unit (e.g., "10 KB", "5.5 MB", "1 GB"). Supported units are:
16
+ * - B (bytes)
17
+ * - KB (kilobytes)
18
+ * - MB (megabytes)
19
+ * - GB (gigabytes)
20
+ * - TB (terabytes)
21
+ *
22
+ * @returns The size in bytes as a number, or `undefined` if the input format is invalid
23
+ * or the value is negative.
24
+ *
25
+ * @example
26
+ * ```typescript
27
+ * toBytes("10 KB") // Returns 10240
28
+ * toBytes("5.5 MB") // Returns 5767168
29
+ * toBytes("1 GB") // Returns 1073741824
30
+ * toBytes("invalid") // Returns undefined
31
+ * ```
32
+ */
33
+ export declare const toBytes: (size: string) => number | undefined;
@@ -16,3 +16,15 @@ export declare const formatTime: (seconds: number) => string;
16
16
  * @returns A formatted string (e.g., "2h 15m 30s").
17
17
  */
18
18
  export declare const formatDuration: (ms: number) => string;
19
+ /**
20
+ * Converts a time string into seconds.
21
+ *
22
+ * Supports various formats:
23
+ * - Direct seconds (e.g., '2947')
24
+ * - MM:SS or HH:MM:SS
25
+ * - 'Xh Ym Zs' format (e.g., '2h 15m 30s')
26
+ *
27
+ * @param time - The time string to convert.
28
+ * @returns The total number of seconds, or undefined if the format is invalid.
29
+ */
30
+ export declare const toSeconds: (time: string) => number | undefined;
@@ -34,3 +34,17 @@ export declare const isArray: <T>(value: unknown) => value is T[];
34
34
  * @returns True if the value is empty, false otherwise.
35
35
  */
36
36
  export declare const isEmpty: (value: unknown) => boolean;
37
+ /**
38
+ * Determines whether a value is valid JSON.
39
+ *
40
+ * This function checks if a value can be parsed as JSON.
41
+ *
42
+ * @param value - The value to check.
43
+ * @returns True if the value is valid JSON, false otherwise.
44
+ *
45
+ * @example
46
+ * isJson('{"name": "John"}'); // true
47
+ * isJson('{invalid}'); // false
48
+ *
49
+ */
50
+ export declare const isJSON: (value: string) => boolean;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@germondai/ts-utils",
3
- "version": "0.0.1",
3
+ "version": "0.0.3",
4
4
  "description": "Germond's TypeScript Utilities",
5
5
  "repository": {
6
6
  "type": "git",