@jsb188/app 1.0.0

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.
@@ -0,0 +1,115 @@
1
+ /**
2
+ * Check if number
3
+ */
4
+
5
+ export function isNumber(input: unknown): input is number {
6
+ switch (typeof input) {
7
+ case 'number':
8
+ return input - input === 0;
9
+ case 'string':
10
+ return input.trim() !== '' && !Number.isNaN(Number(input));
11
+ }
12
+ return false;
13
+ }
14
+
15
+ /**
16
+ * Allow double digit numbers to be represented by a letter
17
+ */
18
+
19
+ export function numberToLetter(num: number, alphabet: string = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ') {
20
+ return alphabet.charAt(num);
21
+ }
22
+
23
+ /**
24
+ * Convert the letter (from above fn()) back to a number;
25
+ */
26
+
27
+ export function letterToNumber(letter: string, alphabet: string = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ') {
28
+ return alphabet.indexOf(letter);
29
+ }
30
+
31
+ /**
32
+ * Get number representation of version number
33
+ */
34
+
35
+ export function versionToNumber(version: string) {
36
+ const arr = String(version).split('.');
37
+ return arr.reduce((acc: number, num: string, n) => {
38
+ let val;
39
+ let minorVal;
40
+ if (!isNaN(Number(num))) {
41
+ val = Number(num);
42
+ minorVal = 0;
43
+ } else {
44
+ // NOTE: Use this to make minor version same as without the letter
45
+ val = Number(num.replace(/\D/g, ''));
46
+ minorVal = letterToNumber(num.replace(/[0-9]/g, ''));
47
+ // console.log('->', num, val, minorVal);
48
+ }
49
+ // console.log(acc + Math.pow(100, 4 - n) * val);
50
+
51
+ return acc + Math.pow(100, 4 - n) * val + minorVal;
52
+ }, 0);
53
+ }
54
+
55
+ /**
56
+ * Format Bytes
57
+ */
58
+
59
+ export function formatBytes(bytes: number, decimals: number = 0) {
60
+ if (!+bytes) {
61
+ return '0 Bytes';
62
+ }
63
+
64
+ const k = 1024;
65
+ const dm = decimals < 0 ? 0 : decimals;
66
+ const sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];
67
+
68
+ const i = Math.floor(Math.log(bytes) / Math.log(k));
69
+ return `${parseFloat((bytes / Math.pow(k, i)).toFixed(dm))} ${sizes[i]}`;
70
+ }
71
+
72
+ /**
73
+ * Convert number (seconds) to human-friendly time
74
+ */
75
+
76
+ export function secondsToTime(secs: number) {
77
+ if (secs < 60) {
78
+ return {
79
+ value: secs,
80
+ unit: 's',
81
+ };
82
+ } else if (secs >= 604800) {
83
+ const weeks = Math.floor(secs / 604800);
84
+ return {
85
+ value: weeks,
86
+ unit: 'w',
87
+ };
88
+ } else if (secs >= 86400) {
89
+ const days = Math.floor(secs / 86400);
90
+ return {
91
+ value: days,
92
+ unit: 'd',
93
+ };
94
+ } else if (secs >= 3600) {
95
+ const hours = Math.floor(secs / 3600);
96
+ return {
97
+ value: hours,
98
+ unit: 'h',
99
+ };
100
+ }
101
+
102
+ const minutes = Math.floor((secs % 3600) / 60);
103
+ return {
104
+ value: minutes,
105
+ unit: 'm',
106
+ };
107
+ }
108
+
109
+ /**
110
+ * Get percentage between 2 values
111
+ */
112
+
113
+ export function calculateDiscount(normalPrice: number, discountedPrice: number) {
114
+ return Math.round(((normalPrice - discountedPrice) / normalPrice) * 100);
115
+ }
@@ -0,0 +1,367 @@
1
+ /**
2
+ * Filter array and return only unique values
3
+ */
4
+
5
+ export function uniq(arr: Array<any>, fn?: (value: any, index: number, self: Array<any>) => boolean) {
6
+ return arr.filter((value, index, self) => {
7
+ return self.indexOf(value) === index && (!fn || fn(value, index, self));
8
+ });
9
+ }
10
+
11
+ /**
12
+ * Freeze object
13
+ * NOTE: This is useful for preventing Array from turning into Array-like Object
14
+ */
15
+
16
+ // export function freezeObject(obj: object) {
17
+ // if (Array.isArray(obj)) {
18
+ // Object.freeze(obj);
19
+ // }
20
+
21
+ // for (const key in obj) {
22
+ // if (Object.prototype.hasOwnProperty.call(obj, key) && typeof obj[key] === 'object') {
23
+ // freezeObject(obj[key]);
24
+ // }
25
+ // }
26
+ // }
27
+
28
+ /**
29
+ * Remove undefined (and/or null) values from an object
30
+ */
31
+
32
+ export function removeUndefined(obj: any, removeNull?: boolean) {
33
+ for (const key in obj) {
34
+ if (Object.prototype.hasOwnProperty.call(obj, key)) {
35
+ if (obj[key] === undefined || (removeNull && obj[key] === null)) {
36
+ delete obj[key];
37
+ } else if (typeof obj[key] === 'object') {
38
+ removeUndefined(obj[key], removeNull);
39
+ }
40
+ }
41
+ }
42
+ return obj;
43
+ }
44
+
45
+ /**
46
+ * Try/catch parse JSON object
47
+ */
48
+
49
+ export function parseJSON(jsonStr?: string) {
50
+ if (jsonStr === undefined || jsonStr === null) {
51
+ return null;
52
+ }
53
+
54
+ try {
55
+ return JSON.parse(jsonStr);
56
+ } catch (err) {
57
+ console.warn(err);
58
+ }
59
+ return null;
60
+ }
61
+
62
+ /**
63
+ * Merge nested objects together
64
+ */
65
+
66
+ export function mergeNestedObjects(obj1: any, obj2: any) {
67
+ if (!obj1) {
68
+ return { ...obj2 };
69
+ }
70
+
71
+ const newObj = { ...obj1 };
72
+ for (const key in obj2) {
73
+ if (Object.prototype.hasOwnProperty.call(obj2, key)) {
74
+ if (typeof obj2[key] === 'object' && obj2[key] !== null) {
75
+ newObj[key] = mergeNestedObjects(obj1[key], obj2[key]);
76
+ } else {
77
+ newObj[key] = obj2[key];
78
+ }
79
+ }
80
+ }
81
+
82
+ return newObj;
83
+ }
84
+
85
+ /**
86
+ * Check if objects are equal
87
+ */
88
+
89
+ export function areObjectsEqual(
90
+ obj1: any,
91
+ obj2: any,
92
+ isNested: boolean = false,
93
+ ) {
94
+ if (isNested) {
95
+ return JSON.stringify(obj1) === JSON.stringify(obj2);
96
+ } else if (obj1 && obj2) {
97
+ return Object.keys(obj1).every((key: string) => Object.prototype.hasOwnProperty.call(obj2, key) && obj1[key] === obj2[key]);
98
+ }
99
+ return obj1 === obj2;
100
+ }
101
+
102
+ /**
103
+ * Order an array of objects by a key
104
+ */
105
+
106
+ export function orderBy(
107
+ arr: Array<any>,
108
+ key: ((obj: any) => any) | string,
109
+ order: 'asc' | 'desc' = 'asc',
110
+ ) {
111
+ const compareFn = (a: any, b: any) => {
112
+ const valueA = typeof key === 'function' ? key(a) : a[key];
113
+ const valueB = typeof key === 'function' ? key(b) : b[key];
114
+
115
+ if (valueA < valueB) {
116
+ return order === 'asc' ? -1 : 1;
117
+ }
118
+ if (valueA > valueB) {
119
+ return order === 'asc' ? 1 : -1;
120
+ }
121
+ return 0;
122
+ };
123
+
124
+ return arr.sort(compareFn);
125
+ }
126
+
127
+ /**
128
+ * Group array by something
129
+ */
130
+
131
+ export function groupBy(arr: Array<any>, key: string) {
132
+ return arr.reduce((acc, obj) => {
133
+ const group = obj[key];
134
+ acc[group] = acc[group] || [];
135
+ acc[group].push(obj);
136
+ return acc;
137
+ }, {});
138
+ }
139
+
140
+ /**
141
+ * Make sure each array item is unique by a key check
142
+ */
143
+
144
+ export function uniqBy(arr: any[], keys: ((obj: any) => any) | string) {
145
+ let keyGetter;
146
+ if (typeof keys === 'function') {
147
+ keyGetter = keys;
148
+ } else if (Array.isArray(keys)) {
149
+ keyGetter = (o: any) => keys.map((k) => get(o, k)).join('');
150
+ } else {
151
+ keyGetter = (o: any) => get(o, keys);
152
+ }
153
+
154
+ return arr.filter((obj, index, self) => {
155
+ const key = keyGetter(obj);
156
+ return self.findIndex((obj2) => {
157
+ const key2 = keyGetter(obj2);
158
+ return key2 === key;
159
+ }) === index;
160
+ });
161
+ }
162
+
163
+ /**
164
+ * Pick a random item from an array
165
+ */
166
+
167
+ export function randomItem(arr: Array<any>) {
168
+ return arr[Math.floor(Math.random() * arr.length)];
169
+ }
170
+
171
+ /**
172
+ * Rearrange an array left or right
173
+ */
174
+
175
+ export function rearrangeArray(arr: Array<any>, loop: number = 1, shiftRight?: boolean) {
176
+ if (shiftRight) {
177
+ for (let i = 0; i < loop; i++) {
178
+ arr.unshift(arr.pop());
179
+ }
180
+ } else {
181
+ for (let i = 0; i < loop; i++) {
182
+ arr.push(arr.shift());
183
+ }
184
+ }
185
+ }
186
+
187
+ /**
188
+ * Get the value in an object at path separted by dots
189
+ */
190
+
191
+ export function get(object: any, path: string) {
192
+ return path.split('.').reduce((o, key) => o && o[key], object);
193
+ }
194
+
195
+ /**
196
+ * Zip objects together from a list of alternating keys and values
197
+ * NOTE: Use this after Redis.hgetall()
198
+ */
199
+
200
+ export function hgetZipObject(arr: Array<string>, mapperFn?: (value: string, index: number) => any) {
201
+ const obj: Record<string, any> = {};
202
+ for (let i = 0; i < arr.length; i += 2) {
203
+ if (mapperFn) {
204
+ obj[arr[i]] = mapperFn(arr[i + 1], i);
205
+ } else {
206
+ obj[arr[i]] = arr[i + 1];
207
+ }
208
+ }
209
+ return obj;
210
+ }
211
+
212
+ /**
213
+ * Zip objects from keys and values
214
+ */
215
+
216
+ export function zipObject(keys: Array<string>, values: Array<any>) {
217
+ const obj: Record<string, any> = {};
218
+ for (let i = 0; i < keys.length; i++) {
219
+ obj[keys[i]] = values[i];
220
+ }
221
+ return obj;
222
+ }
223
+
224
+ /**
225
+ * Find last index of an item in an array
226
+ * NOTE: Use this for best NodeJS and browser compatibility
227
+ */
228
+
229
+ export function findLastIndex(arr: Array<any>, fn: (value: any, index: number, array: any[]) => boolean) {
230
+ if (typeof arr.findLastIndex === 'function') {
231
+ return arr.findLastIndex(fn);
232
+ }
233
+
234
+ for (let i = arr.length - 1; i >= 0; i--) {
235
+ if (fn(arr[i], i, arr)) {
236
+ return i;
237
+ }
238
+ }
239
+ return -1;
240
+ }
241
+
242
+ /**
243
+ * Array intersection
244
+ */
245
+
246
+ export function intersection(arr1: Array<any>, arr2: Array<any>) {
247
+ return arr1.filter((value) => arr2.includes(value));
248
+ }
249
+
250
+ /**
251
+ * Group a collection and merge array fields
252
+ * NOTE: Use this after a findAll() query with inner collections
253
+ */
254
+
255
+ export function groupCollections(collections: Array<any>, innerCollectionNames: string[], primaryKeyName = 'id'): any[] {
256
+ return collections.reduce((acc, obj) => {
257
+ const primaryKey = obj[primaryKeyName];
258
+ const i = acc.findIndex((o: any) => o[primaryKeyName] === primaryKey);
259
+
260
+ if (i === -1) {
261
+ innerCollectionNames.forEach((name: string) => {
262
+ if (!obj[name]) {
263
+ obj[name] = [];
264
+ } else {
265
+ obj[name] = [obj[name]];
266
+ }
267
+ });
268
+
269
+ acc.push(obj);
270
+ } else {
271
+ innerCollectionNames.forEach((name: string) => {
272
+ const innerObj = obj[name];
273
+ if (!acc[i][name]) {
274
+ acc[i][name] = innerObj ? [innerObj] : [];
275
+ } else if (innerObj && !acc[i][name].find((o: any) => o.id === innerObj.id)) {
276
+ acc[i][name].push(obj[name]);
277
+ // .filter((inner, ii, self) => self.findIndex((other) => inner.id === other.id) === ii);
278
+ }
279
+ });
280
+ }
281
+
282
+ return acc;
283
+ }, []);
284
+ }
285
+
286
+ /**
287
+ * Check if Object is array-like, then convert to plain Object.
288
+ * NOTE: This happens a lot when using JS Map()
289
+ * NOTE: This assumes that the keys are ordered numbers
290
+ * NOTE: This function always clones the object.
291
+ */
292
+
293
+ export function cloneArrayLike(obj: any) {
294
+ if (
295
+ !Array.isArray(obj) &&
296
+ Object.keys(obj).every((key, i) => key === i.toString())
297
+ ) {
298
+ return Object.values(obj);
299
+ }
300
+ return { ...obj };
301
+ }
302
+
303
+ // /**
304
+ // * Make a list of possible permutations (all arrangements)
305
+ // * (All permutations using all words)
306
+ // */
307
+
308
+ // function makePermutations(words: string[]): string[][] {
309
+ // const len = words.length;
310
+ // const permutations: string[][] = [];
311
+
312
+ // if (words.length === 0) {
313
+ // return [];
314
+ // }
315
+
316
+ // if (words.length === 1) {
317
+ // return [words];
318
+ // }
319
+
320
+ // for (let i = 0; i < len; i++) {
321
+ // const current = words[i];
322
+ // const other = words.slice(0, i).concat(words.slice(i + 1));
323
+ // const otherPermutations = makePermutations(other);
324
+ // const otherLen = otherPermutations.length;
325
+
326
+ // for (let j = 0; j < otherLen; j++) {
327
+ // const permutation = [current].concat(otherPermutations[j]);
328
+ // permutations.push(permutation);
329
+ // }
330
+ // }
331
+
332
+ // return permutations;
333
+ // }
334
+
335
+ // /**
336
+ // * Find all combinations of an array of words
337
+ // * (All permutations but including incomplete words)
338
+ // * @returns Array of strings (not array of combination arrays)
339
+ // */
340
+
341
+ // function findAllCombinations(words: string[], delimiter: string = ' '): string[] {
342
+
343
+ // const result: string[] = [];
344
+
345
+ // const generateCombinations = (prefix: string, remainingWords: string[]) => {
346
+ // for (let i = 0; i < remainingWords.length; i++) {
347
+ // const newPrefix = prefix ? `${prefix}${delimiter}${remainingWords[i]}` : remainingWords[i];
348
+ // result.push(newPrefix);
349
+ // generateCombinations(newPrefix, remainingWords.slice(i + 1));
350
+ // }
351
+ // };
352
+
353
+ // generateCombinations('', words);
354
+
355
+ // return result;
356
+ // }
357
+
358
+ // // console.log(makePermutations(['a','b','c']));
359
+ // // console.log(findAllCombinations(['a','b','c']));
360
+
361
+ // Leetcode steps
362
+ // 1. Do the steps of the solution manually to visualize it & confirm it to the interviewer
363
+ // 2. Consider 3 ways to solve the problem
364
+ // -> 2a. Array loops
365
+ // -> 2b. Object indexes
366
+ // -> 2c. Human approaches
367
+ // -> Instead of loop, in a loop, get only what you need and then save it in a temp variable
@@ -0,0 +1,211 @@
1
+ const NOT_ALLOWED_USERNAMES = [
2
+ 'ai',
3
+ 'kajiwoto',
4
+ ];
5
+
6
+ /**
7
+ * Combine list of class names
8
+ */
9
+
10
+ export function cn(...classNames: (string | boolean | undefined | null)[]) {
11
+ return classNames.filter(Boolean).join(' ');
12
+ }
13
+
14
+ /**
15
+ * Shorten text to space with length limit
16
+ */
17
+
18
+ export function shortenToSpace(
19
+ str: string,
20
+ len: number = 100,
21
+ ellipsis: string = '...',
22
+ ): string {
23
+ if (!str || str.length < len) {
24
+ return str;
25
+ }
26
+
27
+ const trimmed = str.substring(0, len);
28
+ const spaceIndex = trimmed.lastIndexOf(' ');
29
+
30
+ if (spaceIndex < 0) {
31
+ return trimmed.substring(0, len) + ellipsis;
32
+ }
33
+
34
+ return (
35
+ trimmed.substring(0, Math.min(trimmed.length, spaceIndex)) +
36
+ ellipsis
37
+ );
38
+ }
39
+
40
+ /**
41
+ * Shorten word to space, and remove article words
42
+ */
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
+ }
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
+ }
62
+
63
+ /**
64
+ * Check if e-mail
65
+ */
66
+
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
+ }
73
+
74
+ /**
75
+ * Check if valid username
76
+ */
77
+
78
+ 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
+ );
84
+ }
85
+
86
+ /**
87
+ * Check if password is secure enough
88
+ * Rules:
89
+ * at least 8 characters long
90
+ * at least one lowercase letter
91
+ * at least one uppercase letter
92
+ * at least one special character
93
+ */
94
+
95
+ 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
+ };
112
+ }
113
+
114
+ /**
115
+ * Get time base unique string
116
+ */
117
+
118
+ export function getTimeBasedUnique() {
119
+ return Date.now().toString(36) + Math.random().toString(36).substring(2);
120
+ }
121
+
122
+ /**
123
+ * Convert string to alphanumeric (or space) only
124
+ */
125
+
126
+ export function getAlphanumeric(str: string, space: boolean = false) {
127
+ return str.replace(space ? /[^a-z0-9\s]/gi : /[^a-z0-9]/gi, '');
128
+ }
129
+
130
+ /**
131
+ * Get regex patterns from a text
132
+ */
133
+
134
+ 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
+ );
144
+ }
145
+
146
+ /**
147
+ * Upper case first letter
148
+ */
149
+
150
+ export function ucFirst(str: string) {
151
+ return str.charAt(0).toUpperCase() + str.slice(1);
152
+ }
153
+
154
+ /**
155
+ * Convert cameCalsed string to dash-separated
156
+ */
157
+
158
+ 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
+ });
165
+ }
166
+
167
+ /**
168
+ * Shorten text to a paragraph length
169
+ */
170
+
171
+ 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);
196
+ }
197
+
198
+ /**
199
+ * Use this to validate if a string is empty or invisible
200
+ */
201
+
202
+ export function isInvisibleString(str: string) {
203
+ if (!str?.trim()) {
204
+ return true;
205
+ }
206
+
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();
211
+ }