dhavaltank-js-utils 0.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/dist/index.cjs ADDED
@@ -0,0 +1,399 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+ var __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from === "object" || typeof from === "function") {
12
+ for (let key of __getOwnPropNames(from))
13
+ if (!__hasOwnProp.call(to, key) && key !== except)
14
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
+ }
16
+ return to;
17
+ };
18
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
+
20
+ // src/index.ts
21
+ var src_exports = {};
22
+ __export(src_exports, {
23
+ capitalizeFirstLetter: () => capitalizeFirstLetter,
24
+ checkNotNullAndNotEmpty: () => checkNotNullAndNotEmpty,
25
+ clearLocalStorage: () => clearLocalStorage,
26
+ compareArrays: () => compareArrays,
27
+ formatCurrency: () => formatCurrency,
28
+ generateOTPWithLength: () => generateOTPWithLength,
29
+ generateRandomPassword: () => generateRandomPassword,
30
+ getGreeting: () => getGreeting,
31
+ getInitials: () => getInitials,
32
+ getLocalStorage: () => getLocalStorage,
33
+ getTruncateDescription: () => getTruncateDescription,
34
+ groupBy: () => groupBy,
35
+ handleNaN: () => handleNaN,
36
+ isFalsy: () => isFalsy,
37
+ isObjectValuesEmpty: () => isObjectValuesEmpty,
38
+ isTruthy: () => isTruthy,
39
+ removeDuplicatesFromArray: () => removeDuplicatesFromArray,
40
+ removeLocalStorage: () => removeLocalStorage,
41
+ reverseString: () => reverseString,
42
+ setLocalStorage: () => setLocalStorage,
43
+ slugify: () => slugify,
44
+ sortArrayByMode: () => sortArrayByMode,
45
+ titleCase: () => titleCase,
46
+ validateEmail: () => validateEmail,
47
+ validateMobileNumber: () => validateMobileNumber,
48
+ validatePassword: () => validatePassword,
49
+ validateText: () => validateText
50
+ });
51
+ module.exports = __toCommonJS(src_exports);
52
+
53
+ // src/functions/index.ts
54
+ var capitalizeFirstLetter = (str) => {
55
+ try {
56
+ if (!str)
57
+ return null;
58
+ return str?.trim()?.length > 0 ? str?.charAt(0).toUpperCase() + str?.slice(1) : "";
59
+ } catch (error) {
60
+ console.error(error);
61
+ return null;
62
+ }
63
+ };
64
+ var titleCase = (str, key) => {
65
+ try {
66
+ if (!str)
67
+ return null;
68
+ const text = str.replace(/_/g, " ").split(" ").map((word) => word.charAt(0).toUpperCase() + word.slice(1)).join(" ");
69
+ return key === "And" ? text.replace("And", "&") : text;
70
+ } catch (error) {
71
+ console.error(error);
72
+ return null;
73
+ }
74
+ };
75
+ var getInitials = (name) => {
76
+ try {
77
+ if (typeof name !== "string" || name.trim() === "")
78
+ return "?";
79
+ const words = name.trim().split(" ").map((latter) => latter[0].toUpperCase()).join("");
80
+ return words.length > 1 ? words[0] + words[words.length - 1] : words;
81
+ } catch (error) {
82
+ console.error(error);
83
+ }
84
+ };
85
+ var getTruncateDescription = (text, maxLength = 10) => {
86
+ try {
87
+ return !text ? "" : text.length <= maxLength ? text : `${text.substring(0, maxLength)}...`;
88
+ } catch (error) {
89
+ console.error(error);
90
+ return null;
91
+ }
92
+ };
93
+ var compareArrays = (arr1, arr2) => {
94
+ try {
95
+ return arr1.length === arr2.length && arr1.slice().sort().every((value, index) => value === arr2.slice().sort()[index]);
96
+ } catch (error) {
97
+ console.error(error);
98
+ return null;
99
+ }
100
+ };
101
+ var generateOTPWithLength = (length, isAlphaNumeric = false) => {
102
+ try {
103
+ if (isAlphaNumeric) {
104
+ const characters = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
105
+ return Array.from({ length }, () => characters.charAt(Math.floor(Math.random() * characters.length))).join("");
106
+ } else {
107
+ return Math.floor(Math.random() * (Math.pow(10, length) - Math.pow(10, length - 1) + 1)) + Math.pow(10, length - 1);
108
+ }
109
+ } catch (error) {
110
+ console.error(error);
111
+ }
112
+ };
113
+ var generateRandomPassword = (length = 8) => {
114
+ try {
115
+ const lowercaseChars = "abcdefghijklmnopqrstuvwxyz";
116
+ const uppercaseChars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
117
+ const digitChars = "0123456789";
118
+ const specialChars = "!@#$%^&*()-_=+";
119
+ let password = "";
120
+ password += lowercaseChars.charAt(Math.floor(Math.random() * lowercaseChars.length));
121
+ password += uppercaseChars.charAt(Math.floor(Math.random() * uppercaseChars.length));
122
+ password += digitChars.charAt(Math.floor(Math.random() * digitChars.length));
123
+ for (let i = password.length; i < length; i++) {
124
+ const randomIndex = Math.floor(Math.random() * (lowercaseChars + uppercaseChars + digitChars + specialChars).length);
125
+ password += (lowercaseChars + uppercaseChars + digitChars + specialChars).charAt(randomIndex);
126
+ }
127
+ return password;
128
+ } catch (error) {
129
+ console.error(error);
130
+ return null;
131
+ }
132
+ };
133
+ var slugify = (string, separator = "-") => {
134
+ try {
135
+ return string.trim() ? string.toString().toLowerCase().trim().replace(/\s+/g, separator).replace(/[^\w\-]+/g, "").replace(/\_/g, separator).replace(/\-\-+/g, separator).replace(/\-$/g, "") : "";
136
+ } catch (error) {
137
+ console.error(error);
138
+ return null;
139
+ }
140
+ };
141
+ var setLocalStorage = (key, data) => {
142
+ try {
143
+ localStorage.setItem(key, JSON.stringify(data));
144
+ return true;
145
+ } catch (error) {
146
+ console.error(`Error setting data in localStorage for key "${key}":`, error);
147
+ return false;
148
+ }
149
+ };
150
+ var getLocalStorage = (key) => {
151
+ try {
152
+ const storedData = localStorage.getItem(key);
153
+ return storedData ? JSON.parse(storedData) : null;
154
+ } catch (error) {
155
+ console.error(`Error retrieving data from localStorage for key "${key}":`, error);
156
+ return false;
157
+ }
158
+ };
159
+ var removeLocalStorage = (key) => {
160
+ try {
161
+ localStorage.removeItem(key);
162
+ return true;
163
+ } catch (error) {
164
+ console.error(`Error removing data from localStorage for key "${key}":`, error);
165
+ return false;
166
+ }
167
+ };
168
+ var clearLocalStorage = () => {
169
+ try {
170
+ localStorage.clear();
171
+ return true;
172
+ } catch (error) {
173
+ console.error("Error clearing localStorage:", error);
174
+ return false;
175
+ }
176
+ };
177
+ var getGreeting = () => {
178
+ try {
179
+ const greetings = {
180
+ morning: "Good morning!",
181
+ afternoon: "Good afternoon!",
182
+ evening: "Good evening!"
183
+ };
184
+ const currentHour = (/* @__PURE__ */ new Date()).getHours();
185
+ if (currentHour >= 5 && currentHour < 12)
186
+ return greetings.morning;
187
+ else if (currentHour >= 12 && currentHour < 17)
188
+ return greetings.afternoon;
189
+ else
190
+ return greetings.evening;
191
+ } catch (error) {
192
+ return null;
193
+ }
194
+ };
195
+ var validateText = (value, errorMessage = null) => {
196
+ try {
197
+ if (!value?.trim())
198
+ return { isError: true, errorMessage: errorMessage || "This field must not be empty." };
199
+ const regex = /^[a-zA-Z ]+$/;
200
+ if (!regex.test(value?.trim())) {
201
+ return { isError: true, errorMessage: errorMessage || "Invalid input" };
202
+ }
203
+ return { isError: false, errorMessage: "Valid input" };
204
+ } catch (error) {
205
+ console.error(error);
206
+ return { isError: true, message: "Something went wrong." };
207
+ }
208
+ };
209
+ var validateEmail = (email, errorMessage = null) => {
210
+ try {
211
+ if (!email?.trim())
212
+ return { isError: true, errorMessage: errorMessage || "This field must not be empty." };
213
+ var re = /^(([^<>()[\]\\.,;:\s@"]+(\.[^<>()[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
214
+ if (!re.test(email?.trim())) {
215
+ return { isError: true, errorMessage: errorMessage || "Invalid email" };
216
+ }
217
+ return { isError: false, errorMessage: "Valid email" };
218
+ } catch (error) {
219
+ console.error(error);
220
+ return { isError: true, message: "Something went wrong." };
221
+ }
222
+ };
223
+ var validatePassword = (password, errorMessage = null) => {
224
+ try {
225
+ if (!password?.trim())
226
+ return { isError: true, errorMessage: errorMessage || "This field must not be empty." };
227
+ const regex = /^(?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[!@#$%^&*()_+[\]{};':"\\|,.<>/?]).{8,40}$/;
228
+ if (!regex.test(password?.trim())) {
229
+ return { isError: true, errorMessage: errorMessage || "Password must contain at least 8 characters, including at least one uppercase letter, one lowercase letter, one number, and one symbol." };
230
+ }
231
+ return { isError: false, errorMessage: "Valid password" };
232
+ } catch (error) {
233
+ console.error(error);
234
+ return { isError: true, message: "Something went wrong." };
235
+ }
236
+ };
237
+ var validateMobileNumber = (value, errorMessage = null) => {
238
+ try {
239
+ if (!value?.trim())
240
+ return { isError: true, errorMessage: errorMessage || "This field must not be empty." };
241
+ const regex = /^\d{10}$/;
242
+ if (!regex.test(value?.trim())) {
243
+ return { isError: true, errorMessage: errorMessage || "Invalid mobile number" };
244
+ }
245
+ return { isError: false, errorMessage: "Valid mobile number" };
246
+ } catch (error) {
247
+ console.error(error);
248
+ return { isError: true, message: "Something went wrong." };
249
+ }
250
+ };
251
+ var CurrencyCode = {
252
+ USD: "USD",
253
+ EUR: "EUR",
254
+ GBP: "GBP",
255
+ INR: "INR",
256
+ JPY: "JPY",
257
+ AUD: "AUD",
258
+ CAD: "CAD",
259
+ CHF: "CHF",
260
+ CNY: "CNY"
261
+ };
262
+ var formatCurrency = (number, currencyCode = CurrencyCode.USD, minimumFractionDigits = 2, maximumFractionDigits = 2) => {
263
+ try {
264
+ if (!number)
265
+ return null;
266
+ if (!Object.values(CurrencyCode).includes(currencyCode)) {
267
+ console.warn(`Invalid currency code "${currencyCode}". Defaulting to USD.`);
268
+ currencyCode = CurrencyCode.USD;
269
+ }
270
+ return number?.toLocaleString("en-US", {
271
+ style: "currency",
272
+ currency: currencyCode,
273
+ minimumFractionDigits,
274
+ maximumFractionDigits
275
+ });
276
+ } catch (error) {
277
+ console.error(error);
278
+ return null;
279
+ }
280
+ };
281
+ var removeDuplicatesFromArray = (array) => {
282
+ try {
283
+ return Array.from(new Set(array));
284
+ } catch (error) {
285
+ console.error(error);
286
+ return null;
287
+ }
288
+ };
289
+ var sortArrayByMode = (array, mode = "asc", key = null) => {
290
+ try {
291
+ if (!array || array.length === 0)
292
+ return null;
293
+ if (mode !== "asc" && mode !== "desc") {
294
+ console.error('Invalid sorting mode. Please use "asc" or "desc".');
295
+ return array;
296
+ }
297
+ return [...array].sort((a, b) => {
298
+ const aValue = key !== null ? a[key] : a;
299
+ const bValue = key !== null ? b[key] : b;
300
+ return mode === "asc" ? aValue - bValue : bValue - aValue;
301
+ });
302
+ } catch (error) {
303
+ console.error(error);
304
+ return null;
305
+ }
306
+ };
307
+ var reverseString = (str) => {
308
+ try {
309
+ if (!str)
310
+ return null;
311
+ return str?.split("").reverse().join("");
312
+ } catch (error) {
313
+ console.error(error);
314
+ return null;
315
+ }
316
+ };
317
+ var isObjectValuesEmpty = (object) => {
318
+ const errors = Object.keys(object).reduce((acc, key) => {
319
+ if (!object[key]) {
320
+ acc[key] = key;
321
+ }
322
+ return acc;
323
+ }, {});
324
+ return Object.keys(errors).length > 0;
325
+ };
326
+ var checkNotNullAndNotEmpty = (value) => {
327
+ try {
328
+ if (value !== void 0 && value !== null && value !== "" && value?.toString()?.length !== 0)
329
+ return true;
330
+ else
331
+ return false;
332
+ } catch (error) {
333
+ console.error(error);
334
+ return false;
335
+ }
336
+ };
337
+ var handleNaN = (value, returnValue = 0) => {
338
+ try {
339
+ if (isNaN(value))
340
+ return returnValue;
341
+ else
342
+ return value;
343
+ } catch (error) {
344
+ console.error(error);
345
+ return returnValue;
346
+ }
347
+ };
348
+ var isFalsy = (value) => {
349
+ return !value;
350
+ };
351
+ var isTruthy = (value) => {
352
+ return !!value;
353
+ };
354
+ var groupBy = (arr, key) => {
355
+ try {
356
+ if (!arr)
357
+ return null;
358
+ if (!key)
359
+ return arr;
360
+ return arr.reduce((acc, obj) => {
361
+ const keyValue = obj[key];
362
+ (acc[keyValue] ?? (acc[keyValue] = [])).push(obj);
363
+ return acc;
364
+ }, {});
365
+ } catch (error) {
366
+ console.error(error);
367
+ return null;
368
+ }
369
+ };
370
+ // Annotate the CommonJS export names for ESM import in node:
371
+ 0 && (module.exports = {
372
+ capitalizeFirstLetter,
373
+ checkNotNullAndNotEmpty,
374
+ clearLocalStorage,
375
+ compareArrays,
376
+ formatCurrency,
377
+ generateOTPWithLength,
378
+ generateRandomPassword,
379
+ getGreeting,
380
+ getInitials,
381
+ getLocalStorage,
382
+ getTruncateDescription,
383
+ groupBy,
384
+ handleNaN,
385
+ isFalsy,
386
+ isObjectValuesEmpty,
387
+ isTruthy,
388
+ removeDuplicatesFromArray,
389
+ removeLocalStorage,
390
+ reverseString,
391
+ setLocalStorage,
392
+ slugify,
393
+ sortArrayByMode,
394
+ titleCase,
395
+ validateEmail,
396
+ validateMobileNumber,
397
+ validatePassword,
398
+ validateText
399
+ });
@@ -0,0 +1,69 @@
1
+ type NullableString = string | null | undefined;
2
+ type ArrayType<T> = T[];
3
+ type NumberType = number;
4
+ type AnyType = any;
5
+ type StringType = string;
6
+ type ObjectType = object;
7
+ type BooleanType = boolean;
8
+
9
+ declare const capitalizeFirstLetter: (str: NullableString) => NullableString;
10
+ declare const titleCase: (str: NullableString, key: NullableString) => NullableString;
11
+ declare const getInitials: (name: NullableString) => string | undefined;
12
+ declare const getTruncateDescription: (text: NullableString, maxLength?: number) => string | null;
13
+ declare const compareArrays: <T>(arr1: ArrayType<T>, arr2: ArrayType<T>) => boolean | null;
14
+ declare const generateOTPWithLength: (length: NumberType, isAlphaNumeric?: boolean) => string | number | undefined;
15
+ declare const generateRandomPassword: (length?: number) => string | null;
16
+ declare const slugify: (string: StringType, separator?: string) => string | null;
17
+ declare const setLocalStorage: (key: StringType, data: AnyType) => boolean;
18
+ declare const getLocalStorage: (key: StringType) => any;
19
+ declare const removeLocalStorage: (key: StringType) => boolean;
20
+ declare const clearLocalStorage: () => boolean;
21
+ declare const getGreeting: () => string | null;
22
+ declare const validateText: (value: NullableString, errorMessage?: null) => {
23
+ isError: boolean;
24
+ errorMessage: string;
25
+ message?: undefined;
26
+ } | {
27
+ isError: boolean;
28
+ message: string;
29
+ errorMessage?: undefined;
30
+ };
31
+ declare const validateEmail: (email: NullableString, errorMessage?: null) => {
32
+ isError: boolean;
33
+ errorMessage: string;
34
+ message?: undefined;
35
+ } | {
36
+ isError: boolean;
37
+ message: string;
38
+ errorMessage?: undefined;
39
+ };
40
+ declare const validatePassword: (password: NullableString, errorMessage?: null) => {
41
+ isError: boolean;
42
+ errorMessage: string;
43
+ message?: undefined;
44
+ } | {
45
+ isError: boolean;
46
+ message: string;
47
+ errorMessage?: undefined;
48
+ };
49
+ declare const validateMobileNumber: (value: NullableString, errorMessage?: null) => {
50
+ isError: boolean;
51
+ errorMessage: string;
52
+ message?: undefined;
53
+ } | {
54
+ isError: boolean;
55
+ message: string;
56
+ errorMessage?: undefined;
57
+ };
58
+ declare const formatCurrency: (number: NumberType, currencyCode?: string, minimumFractionDigits?: number, maximumFractionDigits?: number) => string | null;
59
+ declare const removeDuplicatesFromArray: (array: AnyType) => unknown[] | null;
60
+ declare const sortArrayByMode: (array: AnyType, mode?: string, key?: null) => any;
61
+ declare const reverseString: (str: NullableString) => string | null;
62
+ declare const isObjectValuesEmpty: (object: AnyType) => boolean;
63
+ declare const checkNotNullAndNotEmpty: (value: AnyType) => boolean;
64
+ declare const handleNaN: (value: AnyType, returnValue?: number) => any;
65
+ declare const isFalsy: (value: BooleanType) => boolean;
66
+ declare const isTruthy: (value: BooleanType) => boolean;
67
+ declare const groupBy: (arr: AnyType, key: StringType) => any;
68
+
69
+ export { type AnyType, type ArrayType, type BooleanType, type NullableString, type NumberType, type ObjectType, type StringType, capitalizeFirstLetter, checkNotNullAndNotEmpty, clearLocalStorage, compareArrays, formatCurrency, generateOTPWithLength, generateRandomPassword, getGreeting, getInitials, getLocalStorage, getTruncateDescription, groupBy, handleNaN, isFalsy, isObjectValuesEmpty, isTruthy, removeDuplicatesFromArray, removeLocalStorage, reverseString, setLocalStorage, slugify, sortArrayByMode, titleCase, validateEmail, validateMobileNumber, validatePassword, validateText };
@@ -0,0 +1,69 @@
1
+ type NullableString = string | null | undefined;
2
+ type ArrayType<T> = T[];
3
+ type NumberType = number;
4
+ type AnyType = any;
5
+ type StringType = string;
6
+ type ObjectType = object;
7
+ type BooleanType = boolean;
8
+
9
+ declare const capitalizeFirstLetter: (str: NullableString) => NullableString;
10
+ declare const titleCase: (str: NullableString, key: NullableString) => NullableString;
11
+ declare const getInitials: (name: NullableString) => string | undefined;
12
+ declare const getTruncateDescription: (text: NullableString, maxLength?: number) => string | null;
13
+ declare const compareArrays: <T>(arr1: ArrayType<T>, arr2: ArrayType<T>) => boolean | null;
14
+ declare const generateOTPWithLength: (length: NumberType, isAlphaNumeric?: boolean) => string | number | undefined;
15
+ declare const generateRandomPassword: (length?: number) => string | null;
16
+ declare const slugify: (string: StringType, separator?: string) => string | null;
17
+ declare const setLocalStorage: (key: StringType, data: AnyType) => boolean;
18
+ declare const getLocalStorage: (key: StringType) => any;
19
+ declare const removeLocalStorage: (key: StringType) => boolean;
20
+ declare const clearLocalStorage: () => boolean;
21
+ declare const getGreeting: () => string | null;
22
+ declare const validateText: (value: NullableString, errorMessage?: null) => {
23
+ isError: boolean;
24
+ errorMessage: string;
25
+ message?: undefined;
26
+ } | {
27
+ isError: boolean;
28
+ message: string;
29
+ errorMessage?: undefined;
30
+ };
31
+ declare const validateEmail: (email: NullableString, errorMessage?: null) => {
32
+ isError: boolean;
33
+ errorMessage: string;
34
+ message?: undefined;
35
+ } | {
36
+ isError: boolean;
37
+ message: string;
38
+ errorMessage?: undefined;
39
+ };
40
+ declare const validatePassword: (password: NullableString, errorMessage?: null) => {
41
+ isError: boolean;
42
+ errorMessage: string;
43
+ message?: undefined;
44
+ } | {
45
+ isError: boolean;
46
+ message: string;
47
+ errorMessage?: undefined;
48
+ };
49
+ declare const validateMobileNumber: (value: NullableString, errorMessage?: null) => {
50
+ isError: boolean;
51
+ errorMessage: string;
52
+ message?: undefined;
53
+ } | {
54
+ isError: boolean;
55
+ message: string;
56
+ errorMessage?: undefined;
57
+ };
58
+ declare const formatCurrency: (number: NumberType, currencyCode?: string, minimumFractionDigits?: number, maximumFractionDigits?: number) => string | null;
59
+ declare const removeDuplicatesFromArray: (array: AnyType) => unknown[] | null;
60
+ declare const sortArrayByMode: (array: AnyType, mode?: string, key?: null) => any;
61
+ declare const reverseString: (str: NullableString) => string | null;
62
+ declare const isObjectValuesEmpty: (object: AnyType) => boolean;
63
+ declare const checkNotNullAndNotEmpty: (value: AnyType) => boolean;
64
+ declare const handleNaN: (value: AnyType, returnValue?: number) => any;
65
+ declare const isFalsy: (value: BooleanType) => boolean;
66
+ declare const isTruthy: (value: BooleanType) => boolean;
67
+ declare const groupBy: (arr: AnyType, key: StringType) => any;
68
+
69
+ export { type AnyType, type ArrayType, type BooleanType, type NullableString, type NumberType, type ObjectType, type StringType, capitalizeFirstLetter, checkNotNullAndNotEmpty, clearLocalStorage, compareArrays, formatCurrency, generateOTPWithLength, generateRandomPassword, getGreeting, getInitials, getLocalStorage, getTruncateDescription, groupBy, handleNaN, isFalsy, isObjectValuesEmpty, isTruthy, removeDuplicatesFromArray, removeLocalStorage, reverseString, setLocalStorage, slugify, sortArrayByMode, titleCase, validateEmail, validateMobileNumber, validatePassword, validateText };