@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/object.ts CHANGED
@@ -3,9 +3,9 @@
3
3
  */
4
4
 
5
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
- });
6
+ return arr.filter((value, index, self) => {
7
+ return self.indexOf(value) === index && (!fn || fn(value, index, self));
8
+ });
9
9
  }
10
10
 
11
11
  /**
@@ -29,17 +29,36 @@ export function uniq(arr: Array<any>, fn?: (value: any, index: number, self: Arr
29
29
  * Remove undefined (and/or null) values from an object
30
30
  */
31
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;
32
+ export function removeUndefined(obj: Record<string, any>, removeNull?: boolean) {
33
+ for (const key in obj) {
34
+ if (Object.prototype.hasOwnProperty.call(obj, key)) {
35
+ if (
36
+ obj[key] === undefined ||
37
+ (removeNull && obj[key] === null)
38
+ ) {
39
+ delete obj[key];
40
+ } else if (typeof obj[key] === 'object') {
41
+ removeUndefined(obj[key], removeNull);
42
+ }
43
+ }
44
+ }
45
+ return obj;
46
+ }
47
+
48
+ /**
49
+ * Force undefined values to be null instead
50
+ * NOTE: This is useful for database bulkInserts where undefined values in Postgres ORM causes inconsistent queries
51
+ */
52
+
53
+ export function setUndefinedToNull<T>(obj: T, objMap?: Record<string, any>): T {
54
+ for (const key in obj) {
55
+ if (Object.prototype.hasOwnProperty.call(obj, key)) {
56
+ if (obj[key] === undefined) {
57
+ obj[key] = objMap?.[key] ?? null;
58
+ }
59
+ }
60
+ }
61
+ return obj;
43
62
  }
44
63
 
45
64
  /**
@@ -47,16 +66,16 @@ export function removeUndefined(obj: any, removeNull?: boolean) {
47
66
  */
48
67
 
49
68
  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;
69
+ if (jsonStr === undefined || jsonStr === null) {
70
+ return null;
71
+ }
72
+
73
+ try {
74
+ return JSON.parse(jsonStr);
75
+ } catch (err) {
76
+ console.warn(err);
77
+ }
78
+ return null;
60
79
  }
61
80
 
62
81
  /**
@@ -64,22 +83,22 @@ export function parseJSON(jsonStr?: string) {
64
83
  */
65
84
 
66
85
  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;
86
+ if (!obj1) {
87
+ return { ...obj2 };
88
+ }
89
+
90
+ const newObj = { ...obj1 };
91
+ for (const key in obj2) {
92
+ if (Object.prototype.hasOwnProperty.call(obj2, key)) {
93
+ if (typeof obj2[key] === 'object' && obj2[key] !== null) {
94
+ newObj[key] = mergeNestedObjects(obj1[key], obj2[key]);
95
+ } else {
96
+ newObj[key] = obj2[key];
97
+ }
98
+ }
99
+ }
100
+
101
+ return newObj;
83
102
  }
84
103
 
85
104
  /**
@@ -87,16 +106,18 @@ export function mergeNestedObjects(obj1: any, obj2: any) {
87
106
  */
88
107
 
89
108
  export function areObjectsEqual(
90
- obj1: any,
91
- obj2: any,
92
- isNested: boolean = false,
109
+ obj1: any,
110
+ obj2: any,
111
+ isNested: boolean = false,
93
112
  ) {
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;
113
+ if (isNested) {
114
+ return JSON.stringify(obj1) === JSON.stringify(obj2);
115
+ } else if (obj1 && obj2) {
116
+ return Object.keys(obj1).every((key: string) =>
117
+ Object.prototype.hasOwnProperty.call(obj2, key) && obj1[key] === obj2[key]
118
+ );
119
+ }
120
+ return obj1 === obj2;
100
121
  }
101
122
 
102
123
  /**
@@ -104,24 +125,24 @@ export function areObjectsEqual(
104
125
  */
105
126
 
106
127
  export function orderBy(
107
- arr: Array<any>,
108
- key: ((obj: any) => any) | string,
109
- order: 'asc' | 'desc' = 'asc',
128
+ arr: Array<any>,
129
+ key: ((obj: any) => any) | string,
130
+ order: 'asc' | 'desc' = 'asc',
110
131
  ) {
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);
132
+ const compareFn = (a: any, b: any) => {
133
+ const valueA = typeof key === 'function' ? key(a) : a[key];
134
+ const valueB = typeof key === 'function' ? key(b) : b[key];
135
+
136
+ if (valueA < valueB) {
137
+ return order === 'asc' ? -1 : 1;
138
+ }
139
+ if (valueA > valueB) {
140
+ return order === 'asc' ? 1 : -1;
141
+ }
142
+ return 0;
143
+ };
144
+
145
+ return arr.sort(compareFn);
125
146
  }
126
147
 
127
148
  /**
@@ -129,12 +150,12 @@ export function orderBy(
129
150
  */
130
151
 
131
152
  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
- }, {});
153
+ return arr.reduce((acc, obj) => {
154
+ const group = obj[key];
155
+ acc[group] = acc[group] || [];
156
+ acc[group].push(obj);
157
+ return acc;
158
+ }, {});
138
159
  }
139
160
 
140
161
  /**
@@ -142,22 +163,22 @@ export function groupBy(arr: Array<any>, key: string) {
142
163
  */
143
164
 
144
165
  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
- });
166
+ let keyGetter;
167
+ if (typeof keys === 'function') {
168
+ keyGetter = keys;
169
+ } else if (Array.isArray(keys)) {
170
+ keyGetter = (o: any) => keys.map((k) => get(o, k)).join('');
171
+ } else {
172
+ keyGetter = (o: any) => get(o, keys);
173
+ }
174
+
175
+ return arr.filter((obj, index, self) => {
176
+ const key = keyGetter(obj);
177
+ return self.findIndex((obj2) => {
178
+ const key2 = keyGetter(obj2);
179
+ return key2 === key;
180
+ }) === index;
181
+ });
161
182
  }
162
183
 
163
184
  /**
@@ -165,7 +186,7 @@ export function uniqBy(arr: any[], keys: ((obj: any) => any) | string) {
165
186
  */
166
187
 
167
188
  export function randomItem(arr: Array<any>) {
168
- return arr[Math.floor(Math.random() * arr.length)];
189
+ return arr[Math.floor(Math.random() * arr.length)];
169
190
  }
170
191
 
171
192
  /**
@@ -173,15 +194,15 @@ export function randomItem(arr: Array<any>) {
173
194
  */
174
195
 
175
196
  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
- }
197
+ if (shiftRight) {
198
+ for (let i = 0; i < loop; i++) {
199
+ arr.unshift(arr.pop());
200
+ }
201
+ } else {
202
+ for (let i = 0; i < loop; i++) {
203
+ arr.push(arr.shift());
204
+ }
205
+ }
185
206
  }
186
207
 
187
208
  /**
@@ -189,7 +210,7 @@ export function rearrangeArray(arr: Array<any>, loop: number = 1, shiftRight?: b
189
210
  */
190
211
 
191
212
  export function get(object: any, path: string) {
192
- return path.split('.').reduce((o, key) => o && o[key], object);
213
+ return path.split('.').reduce((o, key) => o && o[key], object);
193
214
  }
194
215
 
195
216
  /**
@@ -198,15 +219,15 @@ export function get(object: any, path: string) {
198
219
  */
199
220
 
200
221
  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;
222
+ const obj: Record<string, any> = {};
223
+ for (let i = 0; i < arr.length; i += 2) {
224
+ if (mapperFn) {
225
+ obj[arr[i]] = mapperFn(arr[i + 1], i);
226
+ } else {
227
+ obj[arr[i]] = arr[i + 1];
228
+ }
229
+ }
230
+ return obj;
210
231
  }
211
232
 
212
233
  /**
@@ -214,11 +235,11 @@ export function hgetZipObject(arr: Array<string>, mapperFn?: (value: string, ind
214
235
  */
215
236
 
216
237
  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;
238
+ const obj: Record<string, any> = {};
239
+ for (let i = 0; i < keys.length; i++) {
240
+ obj[keys[i]] = values[i];
241
+ }
242
+ return obj;
222
243
  }
223
244
 
224
245
  /**
@@ -227,16 +248,16 @@ export function zipObject(keys: Array<string>, values: Array<any>) {
227
248
  */
228
249
 
229
250
  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;
251
+ if (typeof arr.findLastIndex === 'function') {
252
+ return arr.findLastIndex(fn);
253
+ }
254
+
255
+ for (let i = arr.length - 1; i >= 0; i--) {
256
+ if (fn(arr[i], i, arr)) {
257
+ return i;
258
+ }
259
+ }
260
+ return -1;
240
261
  }
241
262
 
242
263
  /**
@@ -244,43 +265,116 @@ export function findLastIndex(arr: Array<any>, fn: (value: any, index: number, a
244
265
  */
245
266
 
246
267
  export function intersection(arr1: Array<any>, arr2: Array<any>) {
247
- return arr1.filter((value) => arr2.includes(value));
268
+ return arr1.filter((value) => arr2.includes(value));
248
269
  }
249
270
 
250
271
  /**
251
- * Group a collection and merge array fields
252
- * NOTE: Use this after a findAll() query with inner collections
272
+ * Get a nested value of an object at a property path
273
+ *
274
+ * @param obj - The object to get the value from
275
+ * @param path - The property path as a string, e.g. 'a.b.c'
253
276
  */
254
277
 
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);
278
+ export function getNestedValue(obj: any, path: string): any {
279
+ if (!obj || !path) {
280
+ return undefined;
281
+ }
282
+ return path.split('.').reduce((o, key) => {
283
+ if (o && typeof o === 'object' && key in o) {
284
+ return o[key];
285
+ }
286
+ return undefined;
287
+ }, obj);
288
+ }
289
+
290
+ /**
291
+ * Append value to a nested object
292
+ *
293
+ * @param obj - The object to append to
294
+ * @param path - The property path as a string, e.g. 'a.b.c'
295
+ * @param value - The value to append
296
+ */
297
+
298
+ export function assignToNestedObject(obj: any, path: string, value: any) {
299
+ if (!obj || !path) {
300
+ return;
301
+ }
302
+ const keys = path.split('.');
303
+ const lastKey = keys.pop();
304
+ const nestedObj = keys.reduce((o, key) => {
305
+ if (!o[key]) {
306
+ o[key] = {};
307
+ }
308
+ return o[key];
309
+ }, obj);
310
+
311
+ if (lastKey) {
312
+ if (typeof nestedObj === 'object' && nestedObj !== null) {
313
+ nestedObj[lastKey] = value;
270
314
  } 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
- });
315
+ console.warn(`(!1) Cannot assign value to ${lastKey} because its reference is not an object.`);
280
316
  }
317
+ }
281
318
 
282
- return acc;
283
- }, []);
319
+ return obj;
320
+ }
321
+
322
+ /**
323
+ * Group a collection and merge array fields
324
+ * NOTE: Use this after a findAll() query with inner collections
325
+ *
326
+ * @param collections
327
+ * @param innerCollectionNames
328
+ * @param primaryKeyName
329
+ * @returns
330
+ */
331
+
332
+ export function groupCollections(collections: Array<any>, innerCollectionNames: string[], primaryKeyName = 'id'): any[] {
333
+ return collections.reduce((acc, obj) => {
334
+ const primaryKey = obj[primaryKeyName];
335
+ const i = acc.findIndex((o: any) => o[primaryKeyName] === primaryKey);
336
+
337
+ if (i === -1) {
338
+ innerCollectionNames.forEach((name: string) => {
339
+ const ref = getNestedValue(obj, name);
340
+ if (!ref) {
341
+ assignToNestedObject(obj, name, []);
342
+ } else {
343
+ assignToNestedObject(obj, name, [ref]);
344
+ }
345
+
346
+ // Old version, but this doesn't support merged array collections
347
+ // if (!obj[name]) {
348
+ // obj[name] = [];
349
+ // } else {
350
+ // obj[name] = [obj[name]];
351
+ // }
352
+ });
353
+
354
+ acc.push(obj);
355
+ } else {
356
+ innerCollectionNames.forEach((name: string) => {
357
+ const innerObj = getNestedValue(obj, name);
358
+ const ref = getNestedValue(acc[i], name);
359
+
360
+ if (!ref) {
361
+ assignToNestedObject(acc[i], name, innerObj ? [innerObj] : []);
362
+ } else if (innerObj && !ref.find((o: any) => o.id === innerObj.id)) {
363
+ assignToNestedObject(acc[i], name, ref.concat(innerObj));
364
+ }
365
+
366
+ // Old version, but this doesn't support merged array collections
367
+ // const innerObj = obj[name];
368
+ // if (!acc[i][name]) {
369
+ // acc[i][name] = innerObj ? [innerObj] : [];
370
+ // } else if (innerObj && !acc[i][name].find((o: any) => o.id === innerObj.id)) {
371
+ // acc[i][name].push(obj[name]);
372
+ // }
373
+ });
374
+ }
375
+
376
+ return acc;
377
+ }, []);
284
378
  }
285
379
 
286
380
  /**
@@ -291,77 +385,41 @@ export function groupCollections(collections: Array<any>, innerCollectionNames:
291
385
  */
292
386
 
293
387
  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 };
388
+ if (
389
+ !Array.isArray(obj) &&
390
+ Object.keys(obj).every((key, i) => key === i.toString())
391
+ ) {
392
+ return Object.values(obj);
393
+ }
394
+ return { ...obj };
301
395
  }
302
396
 
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[] = [];
397
+ /**
398
+ * Check if Object is iterable
399
+ */
344
400
 
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
- // };
401
+ export function isIterable(obj: any) {
402
+ return obj != null && typeof obj[Symbol.iterator] === 'function';
403
+ }
352
404
 
353
- // generateCombinations('', words);
405
+ /**
406
+ * Get the last key from a JS Map
407
+ */
354
408
 
355
- // return result;
356
- // }
409
+ export function getLastMapKey(map: Map<any, any>) {
410
+ if (!map || map.size === 0) {
411
+ return undefined;
412
+ }
413
+ return Array.from(map.keys()).pop();
414
+ }
357
415
 
358
- // // console.log(makePermutations(['a','b','c']));
359
- // // console.log(findAllCombinations(['a','b','c']));
416
+ /**
417
+ * Get the first key from a JS Map
418
+ */
360
419
 
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
420
+ export function getFirstMapKey(map: Map<any, any>) {
421
+ if (!map || map.size === 0) {
422
+ return undefined;
423
+ }
424
+ return Array.from(map.keys()).shift();
425
+ }