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