@jsb188/app 1.0.4 → 1.1.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/utils/string.ts CHANGED
@@ -1,6 +1,6 @@
1
1
  const NOT_ALLOWED_USERNAMES = [
2
- 'ai',
3
- 'kajiwoto',
2
+ 'ai',
3
+ 'kajiwoto',
4
4
  ];
5
5
 
6
6
  /**
@@ -8,7 +8,7 @@ const NOT_ALLOWED_USERNAMES = [
8
8
  */
9
9
 
10
10
  export function cn(...classNames: (string | boolean | undefined | null)[]) {
11
- return classNames.filter(Boolean).join(' ');
11
+ return classNames.filter(Boolean).join(' ');
12
12
  }
13
13
 
14
14
  /**
@@ -16,25 +16,25 @@ export function cn(...classNames: (string | boolean | undefined | null)[]) {
16
16
  */
17
17
 
18
18
  export function shortenToSpace(
19
- str: string,
20
- len: number = 100,
21
- ellipsis: string = '...',
19
+ str: string,
20
+ len: number = 100,
21
+ ellipsis: string = '...',
22
22
  ): string {
23
- if (!str || str.length < len) {
24
- return str;
25
- }
23
+ if (!str || str.length < len) {
24
+ return str;
25
+ }
26
26
 
27
- const trimmed = str.substring(0, len);
28
- const spaceIndex = trimmed.lastIndexOf(' ');
27
+ const trimmed = str.substring(0, len);
28
+ const spaceIndex = trimmed.lastIndexOf(' ');
29
29
 
30
- if (spaceIndex < 0) {
31
- return trimmed.substring(0, len) + ellipsis;
32
- }
30
+ if (spaceIndex < 0) {
31
+ return trimmed.substring(0, len) + ellipsis;
32
+ }
33
33
 
34
- return (
35
- trimmed.substring(0, Math.min(trimmed.length, spaceIndex)) +
36
- ellipsis
37
- );
34
+ return (
35
+ trimmed.substring(0, Math.min(trimmed.length, spaceIndex)) +
36
+ ellipsis
37
+ );
38
38
  }
39
39
 
40
40
  /**
@@ -42,33 +42,76 @@ export function shortenToSpace(
42
42
  */
43
43
 
44
44
  export function shortenName(str: string, len: number = 40): string {
45
- const articleReplacedStart = str?.replace(/^(a|an|the|da|de|that|there|this|than|then)\b/i, '') || '';
46
- if (articleReplacedStart.length < 5) {
47
- return shortenToSpace(str, len, '');
48
- }
45
+ const articleReplacedStart = str?.replace(/^(a|an|the|da|de|that|there|this|than|then)\b/i, '') || '';
46
+ if (articleReplacedStart.length < 5) {
47
+ return shortenToSpace(str, len, '');
48
+ }
49
+
50
+ const shortened = shortenToSpace(articleReplacedStart, len, '');
51
+ const articleReplacedEnd = shortened.replace(
52
+ /\b(a|an|the|da|de|that|there|this|than|then)$/i,
53
+ '',
54
+ );
55
+
56
+ if (articleReplacedEnd.length < 5) {
57
+ return shortened;
58
+ }
59
+
60
+ return articleReplacedEnd.trim();
61
+ }
49
62
 
50
- const shortened = shortenToSpace(articleReplacedStart, len, '');
51
- const articleReplacedEnd = shortened.replace(
52
- /\b(a|an|the|da|de|that|there|this|than|then)$/i,
53
- '',
54
- );
63
+ /**
64
+ * Check if e-mail
65
+ */
55
66
 
56
- if (articleReplacedEnd.length < 5) {
57
- return shortened;
58
- }
67
+ export function isEmail(str: string) {
68
+ // return /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(str);
69
+ const emailRegex =
70
+ /[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?/;
71
+ return emailRegex.test(str.trim());
72
+ }
59
73
 
60
- return articleReplacedEnd.trim();
74
+ /**
75
+ * Convert various phone formats to international format
76
+ * @returns phone number in international format
77
+ */
78
+
79
+ export function convertToInternationalPhone(str: string) {
80
+ // Check if string has a character that isn't one of [(, ), +, -, " ", 0-9]
81
+ if (/[^0-9+\-\s().]/.test(str)) {
82
+ // Invalid
83
+ return null;
84
+ }
85
+
86
+ const digits = str.replace(/[^0-9]/g, '');
87
+ if (digits.startsWith('0')) {
88
+ // Invalid
89
+ return null;
90
+ } else if (
91
+ !digits.startsWith('1') &&
92
+ digits.length === 10
93
+ ) {
94
+ return '+1' + digits;
95
+ }
96
+
97
+ // If it doesn't start with a country code, assume it's already in international format
98
+ return '+' + digits;
61
99
  }
62
100
 
63
101
  /**
64
- * Check if e-mail
102
+ * Check if phone number
103
+ * @returns TRUE if starts with + and has 7-15 digits
65
104
  */
66
105
 
67
- export function isEmail(str: string) {
68
- // return /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(str);
69
- const emailRegex =
70
- /[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?/;
71
- return emailRegex.test(str.trim());
106
+ export function isPhone(str: string, doNotConvertInternational: boolean = false) {
107
+ let phoneNumber: string | null = str.trim();
108
+ if (!doNotConvertInternational) {
109
+ phoneNumber = convertToInternationalPhone(phoneNumber);
110
+ if (!phoneNumber) {
111
+ return false;
112
+ }
113
+ }
114
+ return /^\+[0-9]{7,15}$/.test(phoneNumber);
72
115
  }
73
116
 
74
117
  /**
@@ -76,11 +119,11 @@ export function isEmail(str: string) {
76
119
  */
77
120
 
78
121
  export function isValidUsername(str: string) {
79
- const username = str.replace(/^@/, '').toLowerCase();
80
- return (
81
- /^[a-z0-9_]+$/i.test(username) &&
82
- !NOT_ALLOWED_USERNAMES.includes(username)
83
- );
122
+ const username = str.replace(/^@/, '').toLowerCase();
123
+ return (
124
+ /^[a-z0-9_]+$/i.test(username) &&
125
+ !NOT_ALLOWED_USERNAMES.includes(username)
126
+ );
84
127
  }
85
128
 
86
129
  /**
@@ -93,22 +136,22 @@ export function isValidUsername(str: string) {
93
136
  */
94
137
 
95
138
  export function passwordStrength(str: string, minLength: number = 8) {
96
- const isLongEnough = str.length >= minLength;
97
- const hasLowercase = /[a-z]/.test(str);
98
- const hasUppercase = /[A-Z]/.test(str);
99
- const hasDigit = /\d/.test(str);
100
- const hasSpecial = /\W/.test(str);
101
- const valid = isLongEnough && hasLowercase && hasUppercase && hasDigit &&
102
- hasSpecial;
103
- // return /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*\W)[a-zA-Z\d\W]{8,}$/.test(str);
104
- return {
105
- valid,
106
- isLongEnough,
107
- hasLowercase,
108
- hasUppercase,
109
- hasDigit,
110
- hasSpecial,
111
- };
139
+ const isLongEnough = str.length >= minLength;
140
+ const hasLowercase = /[a-z]/.test(str);
141
+ const hasUppercase = /[A-Z]/.test(str);
142
+ const hasDigit = /\d/.test(str);
143
+ const hasSpecial = /\W/.test(str);
144
+ const valid = isLongEnough && hasLowercase && hasUppercase && hasDigit &&
145
+ hasSpecial;
146
+ // return /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*\W)[a-zA-Z\d\W]{8,}$/.test(str);
147
+ return {
148
+ valid,
149
+ isLongEnough,
150
+ hasLowercase,
151
+ hasUppercase,
152
+ hasDigit,
153
+ hasSpecial,
154
+ };
112
155
  }
113
156
 
114
157
  /**
@@ -116,7 +159,7 @@ export function passwordStrength(str: string, minLength: number = 8) {
116
159
  */
117
160
 
118
161
  export function getTimeBasedUnique() {
119
- return Date.now().toString(36) + Math.random().toString(36).substring(2);
162
+ return Date.now().toString(36) + Math.random().toString(36).substring(2);
120
163
  }
121
164
 
122
165
  /**
@@ -124,7 +167,7 @@ export function getTimeBasedUnique() {
124
167
  */
125
168
 
126
169
  export function getAlphanumeric(str: string, space: boolean = false) {
127
- return str.replace(space ? /[^a-z0-9\s]/gi : /[^a-z0-9]/gi, '');
170
+ return str.replace(space ? /[^a-z0-9\s]/gi : /[^a-z0-9]/gi, '');
128
171
  }
129
172
 
130
173
  /**
@@ -132,15 +175,15 @@ export function getAlphanumeric(str: string, space: boolean = false) {
132
175
  */
133
176
 
134
177
  export function regexFromText(text: string) {
135
- const words = getAlphanumeric(text, true).split(/\s+/).filter((s) => s.length >= 2);
136
- if (!words.length) {
137
- return null;
138
- }
139
-
140
- return new RegExp(
141
- '\\b' + (words.length === 1 ? words[0] : '(?:' + words.join('|') + ')'),
142
- 'gi',
143
- );
178
+ const words = getAlphanumeric(text, true).split(/\s+/).filter((s) => s.length >= 2);
179
+ if (!words.length) {
180
+ return null;
181
+ }
182
+
183
+ return new RegExp(
184
+ '\\b' + (words.length === 1 ? words[0] : '(?:' + words.join('|') + ')'),
185
+ 'gi',
186
+ );
144
187
  }
145
188
 
146
189
  /**
@@ -148,7 +191,10 @@ export function regexFromText(text: string) {
148
191
  */
149
192
 
150
193
  export function ucFirst(str: string) {
151
- return str.charAt(0).toUpperCase() + str.slice(1);
194
+ if (!str) {
195
+ return '';
196
+ }
197
+ return str.charAt(0).toUpperCase() + str.slice(1);
152
198
  }
153
199
 
154
200
  /**
@@ -156,12 +202,12 @@ export function ucFirst(str: string) {
156
202
  */
157
203
 
158
204
  export function camelCaseToDash(str: string) {
159
- if (/^[A-Z0-9]+$/.test(str)) {
160
- return str.toLowerCase();
161
- }
162
- return str.replace(/[A-Z0-9]/g, (m, i) => {
163
- return `${i ? '-' : ''}${m.toLowerCase()}`;
164
- });
205
+ if (/^[A-Z0-9]+$/.test(str)) {
206
+ return str.toLowerCase();
207
+ }
208
+ return str.replace(/[A-Z0-9]/g, (m, i) => {
209
+ return `${i ? '-' : ''}${m.toLowerCase()}`;
210
+ });
165
211
  }
166
212
 
167
213
  /**
@@ -169,30 +215,30 @@ export function camelCaseToDash(str: string) {
169
215
  */
170
216
 
171
217
  export function shortenToParagraph(str: string, len: number, replaceDoubleLineBreaks?: boolean) {
172
- let trimedToParagraph = str || '';
173
- if (replaceDoubleLineBreaks) {
174
- trimedToParagraph = trimedToParagraph.replace(/\n\s*\n/g, '\n');
175
- }
176
-
177
- trimedToParagraph = trimedToParagraph.split('\n').reduce((acc, str) => {
178
- if (acc.done) {
179
- return acc;
180
- }
181
- acc.done = (acc.value.length + str.length) >= len;
182
- acc.value = acc.done ? acc.value : acc.value + '\n' + str;
183
- return acc;
184
- }, {
185
- done: false,
186
- value: '',
187
- }).value.trim();
188
-
189
- if (!trimedToParagraph) {
190
- return shortenToSpace(str || '', len);
191
- } else if (trimedToParagraph.length <= len) {
192
- return trimedToParagraph;
193
- }
194
-
195
- return shortenToSpace(trimedToParagraph, len);
218
+ let trimedToParagraph = str || '';
219
+ if (replaceDoubleLineBreaks) {
220
+ trimedToParagraph = trimedToParagraph.replace(/\n\s*\n/g, '\n');
221
+ }
222
+
223
+ trimedToParagraph = trimedToParagraph.split('\n').reduce((acc, str) => {
224
+ if (acc.done) {
225
+ return acc;
226
+ }
227
+ acc.done = (acc.value.length + str.length) >= len;
228
+ acc.value = acc.done ? acc.value : acc.value + '\n' + str;
229
+ return acc;
230
+ }, {
231
+ done: false,
232
+ value: '',
233
+ }).value.trim();
234
+
235
+ if (!trimedToParagraph) {
236
+ return shortenToSpace(str || '', len);
237
+ } else if (trimedToParagraph.length <= len) {
238
+ return trimedToParagraph;
239
+ }
240
+
241
+ return shortenToSpace(trimedToParagraph, len);
196
242
  }
197
243
 
198
244
  /**
@@ -200,12 +246,78 @@ export function shortenToParagraph(str: string, len: number, replaceDoubleLineBr
200
246
  */
201
247
 
202
248
  export function isInvisibleString(str: string) {
203
- if (!str?.trim()) {
204
- return true;
205
- }
249
+ if (!str?.trim()) {
250
+ return true;
251
+ }
252
+
253
+ // eslint-disable-next-line no-misleading-character-class
254
+ const invisRegex = /[ㅤ ️⠀ْٔ]/g;
255
+ const checkStr = str.replace(invisRegex, ' '); // .replace(/[ㅤ ️⠀]/gi, ' ');
256
+ return !checkStr.trim();
257
+ }
258
+
259
+ /**
260
+ * Build a single text block with proper line breaks
261
+ * NOTE: Userful for building AI prompts
262
+ */
263
+
264
+ export function buildSingleText(lines: (string | undefined | false | null)[]) {
265
+ return lines
266
+ .reduce((acc, line_) => {
267
+ const line = line_ || '';
268
+ if (line || acc[acc.length - 1] !== '') {
269
+ acc.push(line);
270
+ }
271
+ return acc;
272
+ }, [] as string[])
273
+ .join('\n')
274
+ .trim();
275
+ }
206
276
 
207
- // eslint-disable-next-line no-misleading-character-class
208
- const invisRegex = /[ㅤ ️⠀ْٔ]/g;
209
- const checkStr = str.replace(invisRegex, ' '); // .replace(/[ㅤ ️⠀]/gi, ' ');
210
- return !checkStr.trim();
277
+ /**
278
+ * Join array of texts but last word has a special separator
279
+ *
280
+ * @param texts - Array of strings to join
281
+ * @param separator - Separator to use between texts
282
+ * @param lastSeparator - Separator to use before the last text
283
+ * @returns Joined string with special last separator
284
+ */
285
+
286
+ export function joinReadable(
287
+ texts: string[],
288
+ separator: string = ', ',
289
+ lastSeparator: string = ' and ',
290
+ ) {
291
+ const lastIx = texts.length - 1;
292
+ return texts.reduce((acc, text, i) => {
293
+ return acc + (!acc ? '' : i === lastIx ? lastSeparator : separator) + text;
294
+ }, '');
295
+ }
296
+
297
+ /**
298
+ * Helper for writing text with optional brackets
299
+ *
300
+ * @param text - Text to write
301
+ * @param bracketsText - Text that will be written in brackets
302
+ * @param brackets - Brackets to use, defaults to round brackets
303
+ * @returns Formatted text with optional brackets
304
+ */
305
+
306
+ export function textWithBrackets(
307
+ text: string,
308
+ bracketsText?: string | string[],
309
+ brackets: [string, string] = ['(', ')']
310
+ ) {
311
+ let bText;
312
+ if (Array.isArray(bracketsText)) {
313
+ bText = bracketsText.filter(Boolean).join(' ').trim();
314
+ } else {
315
+ bText = bracketsText?.trim();
316
+ }
317
+ if (!bText) {
318
+ return text;
319
+ } else if (!text) {
320
+ return bText;
321
+ }
322
+ return `${text} ${brackets[0].trimStart()}${bText}${brackets[1].trimEnd()}`;
211
323
  }