@slickgrid-universal/utils 4.0.2 → 4.1.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.
package/src/utils.ts ADDED
@@ -0,0 +1,399 @@
1
+ /**
2
+ * Add an item to an array only when the item does not exists, when the item is an object we will be using their "id" to compare
3
+ * @param inputArray
4
+ * @param inputItem
5
+ * @param itemIdPropName
6
+ */
7
+ export function addToArrayWhenNotExists<T = any>(inputArray: T[], inputItem: T, itemIdPropName = 'id') {
8
+ let arrayRowIndex = -1;
9
+ if (inputItem && typeof inputItem === 'object' && itemIdPropName in inputItem) {
10
+ arrayRowIndex = inputArray.findIndex((item) => item[itemIdPropName as keyof T] === inputItem[itemIdPropName as keyof T]);
11
+ } else {
12
+ arrayRowIndex = inputArray.findIndex((item) => item === inputItem);
13
+ }
14
+
15
+ if (arrayRowIndex < 0) {
16
+ inputArray.push(inputItem);
17
+ }
18
+ }
19
+
20
+ /**
21
+ * Simple function that will return a string with the number of whitespaces asked, mostly used by the CSV export
22
+ * @param {Number} nbSpaces - number of white spaces to create
23
+ * @param {String} spaceChar - optionally provide a different character to use for the whitespace (e.g. could be override to use "&nbsp;" in html)
24
+ */
25
+ export function addWhiteSpaces(nbSpaces: number, spaceChar = ' '): string {
26
+ let result = '';
27
+
28
+ for (let i = 0; i < nbSpaces; i++) {
29
+ result += spaceChar;
30
+ }
31
+ return result;
32
+ }
33
+
34
+ /**
35
+ * Remove an item from the array by its index
36
+ * @param array input
37
+ * @param index
38
+ */
39
+ export function arrayRemoveItemByIndex<T>(array: T[], index: number): T[] {
40
+ return array.filter((_el: T, i: number) => index !== i);
41
+ }
42
+
43
+ /**
44
+ * Create an immutable clone of an array or object
45
+ * (c) 2019 Chris Ferdinandi, MIT License, https://gomakethings.com
46
+ * @param {Array|Object} objectOrArray - the array or object to copy
47
+ * @return {Array|Object} - the clone of the array or object
48
+ */
49
+ export function deepCopy(objectOrArray: any | any[]): any | any[] {
50
+ /**
51
+ * Create an immutable copy of an object
52
+ * @return {Object}
53
+ */
54
+ const cloneObj = () => {
55
+ // Create new object
56
+ const clone = {};
57
+
58
+ // Loop through each item in the original
59
+ // Recursively copy it's value and add to the clone
60
+ for (const key in objectOrArray) {
61
+ if (Object.prototype.hasOwnProperty.call(objectOrArray, key)) {
62
+ (clone as any)[key] = deepCopy(objectOrArray[key]);
63
+ }
64
+ }
65
+ return clone;
66
+ };
67
+
68
+ /**
69
+ * Create an immutable copy of an array
70
+ * @return {Array}
71
+ */
72
+ const cloneArr = () => objectOrArray.map((item: any) => deepCopy(item));
73
+
74
+ // -- init --//
75
+ // Get object type
76
+ const type = Object.prototype.toString.call(objectOrArray).slice(8, -1).toLowerCase();
77
+
78
+ // If an object
79
+ if (type === 'object') {
80
+ return cloneObj();
81
+ }
82
+ // If an array
83
+ if (type === 'array') {
84
+ return cloneArr();
85
+ }
86
+ // Otherwise, return it as-is
87
+ return objectOrArray;
88
+ }
89
+
90
+ /**
91
+ * Performs a deep merge of objects and returns new object, it does not modify the source object, objects (immutable) and merges arrays via concatenation.
92
+ * Also, if first argument is undefined/null but next argument is an object then it will proceed and output will be an object
93
+ * @param {Object} target - the target object — what to apply the sources' properties to, which is returned after it is modified.
94
+ * @param {Object} sources - the source object(s) — objects containing the properties you want to apply.
95
+ * @returns {Object} The target object.
96
+ */
97
+ export function deepMerge(target: any, ...sources: any[]): any {
98
+ if (!sources.length) {
99
+ return target;
100
+ }
101
+ const source = sources.shift();
102
+
103
+ // when target is not an object but source is an object, then we'll assign as object
104
+ target = (!isObject(target) && isObject(source)) ? {} : target;
105
+
106
+ if (isObject(target) && isObject(source)) {
107
+ for (const prop in source) {
108
+ if (source.hasOwnProperty(prop)) {
109
+ if (prop in target) {
110
+ // handling merging of two properties with equal names
111
+ if (typeof target[prop] !== 'object') {
112
+ target[prop] = source[prop];
113
+ } else {
114
+ if (typeof source[prop] !== 'object') {
115
+ target[prop] = source[prop];
116
+ } else {
117
+ if (target[prop].concat && source[prop].concat) {
118
+ // two arrays get concatenated
119
+ target[prop] = target[prop].concat(source[prop]);
120
+ } else {
121
+ // two objects get merged recursively
122
+ target[prop] = deepMerge(target[prop], source[prop]);
123
+ }
124
+ }
125
+ }
126
+ } else {
127
+ // new properties get added to target
128
+ target[prop] = source[prop];
129
+ }
130
+ }
131
+ }
132
+ }
133
+ return deepMerge(target, ...sources);
134
+ }
135
+
136
+ /**
137
+ * This method is similar to `Object.assign` with the exception that it will also extend the object properties when filled.
138
+ * There's also a distinction with extend vs merge, we are only extending when the property is not filled (if it is filled then it remains untouched and will not be merged)
139
+ * It also applies the change directly on the target object which mutates the original object.
140
+ * For example using these 2 objects: obj1 = { a: 1, b: { c: 2, d: 3 }} and obj2 = { b: { d: 2, e: 3}}:
141
+ * - Object.assign(obj1, obj2) => { a: 1, b: { e: 4 }}
142
+ * - objectAssignAndExtend(obj1, obj2) => { a: 1, b: { c: 2, d: 3, e: 4 }
143
+ * @param {Object} target - the target object — what to apply the sources properties and mutate into
144
+ * @param {Object} sources - the source object(s) — objects containing the properties you want to apply.
145
+ * @returns {Object} The target object.
146
+ */
147
+ export function objectAssignAndExtend(target: any, ...sources: any): any {
148
+ if (!sources.length || sources[0] === undefined) {
149
+ return target;
150
+ }
151
+ const source = sources.shift();
152
+
153
+ // when target is not an object but source is an object, then we'll assign as object
154
+ target = (!isObject(target) && isObject(source)) ? {} : target;
155
+
156
+ if (isObject(target) && isObject(source)) {
157
+ for (const key of Object.keys(source)) {
158
+ if (typeof source[key] === 'object' && source[key] !== null) {
159
+ objectAssignAndExtend(target[key], source[key]);
160
+ }
161
+ if ((target[key] === null || target[key] === undefined) && source[key] !== null && source[key] !== undefined) {
162
+ target[key] = source[key];
163
+ }
164
+ }
165
+ }
166
+ return objectAssignAndExtend(target, ...sources);
167
+ }
168
+
169
+ /**
170
+ * Empty an object properties by looping through them all and deleting them
171
+ * @param obj - input object
172
+ */
173
+ export function emptyObject(obj: any) {
174
+ for (const key in obj) {
175
+ if (obj.hasOwnProperty(key)) {
176
+ delete obj[key];
177
+ }
178
+ }
179
+ obj = null;
180
+ obj = {};
181
+
182
+ return obj;
183
+ }
184
+
185
+ /**
186
+ * Check if an object is empty
187
+ * @param obj - input object
188
+ * @returns - boolean
189
+ */
190
+ export function isEmptyObject(obj: any): boolean {
191
+ if (obj === null || obj === undefined) {
192
+ return true;
193
+ }
194
+ return Object.entries(obj).length === 0;
195
+ }
196
+
197
+ export function isDefined<T>(value: T | undefined | null): value is T {
198
+ return <T>value !== undefined && <T>value !== null && <T>value !== '';
199
+ }
200
+
201
+ /**
202
+ * Simple object check.
203
+ * @param item
204
+ * @returns {boolean}
205
+ */
206
+ export function isObject(item: any) {
207
+ return item !== null && typeof item === 'object' && !Array.isArray(item) && !(item instanceof Date);
208
+ }
209
+
210
+ /**
211
+ * Simple check to detect if the value is a primitive type
212
+ * @param val
213
+ * @returns {boolean}
214
+ */
215
+ export function isPrimitiveValue(val: any) {
216
+ return typeof val === 'boolean' || typeof val === 'number' || typeof val === 'string' || val === null || val === undefined;
217
+ }
218
+
219
+ export function isPrimitiveOrHTML(val: any) {
220
+ return val instanceof HTMLElement || val instanceof DocumentFragment || isPrimitiveValue(val);
221
+ }
222
+
223
+ /**
224
+ * Check if a value has any data (undefined, null or empty string will return False...)
225
+ * NOTE: a `false` boolean is consider as having data so it will return True
226
+ */
227
+ export function hasData(value: any): boolean {
228
+ return value !== undefined && value !== null && value !== '';
229
+ }
230
+
231
+ /**
232
+ * Check if input value is a number, by default it won't be a strict checking
233
+ * but optionally we could check for strict equality, for example in strict "3" will return False but without strict it will return True
234
+ * @param value - input value of any type
235
+ * @param strict - when using strict it also check for strict equality, for example in strict "3" would return False but without strict it would return True
236
+ */
237
+ export function isNumber(value: any, strict = false) {
238
+ if (strict) {
239
+ return (value === null || value === undefined || typeof value === 'string') ? false : !isNaN(value);
240
+ }
241
+ return (value === null || value === undefined || value === '') ? false : !isNaN(+value);
242
+ }
243
+
244
+ /** Check if an object is empty, it will also be considered empty when the input is null, undefined or isn't an object */
245
+ export function isObjectEmpty(obj: unknown) {
246
+ return !obj || (obj && typeof obj === 'object' && Object.keys(obj).length === 0);
247
+ }
248
+
249
+ /** Parse any input (bool, number, string) and return a boolean or False when not possible */
250
+ export function parseBoolean(input: any): boolean {
251
+ return /(true|1)/i.test(input + '');
252
+ }
253
+
254
+ /**
255
+ * Remove any accents from a string by normalizing it
256
+ * @param {String} text - input text
257
+ * @param {Boolean} shouldLowerCase - should we also lowercase the string output?
258
+ * @returns
259
+ */
260
+ export function removeAccentFromText(text: string, shouldLowerCase = false) {
261
+ const normalizedText = (typeof text.normalize === 'function') ? text.normalize('NFD').replace(/[\u0300-\u036f]/g, '') : text;
262
+ return shouldLowerCase ? normalizedText.toLowerCase() : normalizedText;
263
+ }
264
+
265
+ /** Set the object value of deeper node from a given dot (.) notation path (e.g.: "user.firstName") */
266
+ export function setDeepValue<T = unknown>(obj: T, path: string | string[], value: any) {
267
+ if (typeof path === 'string') {
268
+ path = path.split('.');
269
+ }
270
+
271
+ if (path.length > 1) {
272
+ const e = path.shift() as keyof T;
273
+ if (obj && e !== undefined) {
274
+ setDeepValue(
275
+ (obj)[e] = (hasData(obj[e]) && (Array.isArray(obj[e]) || Object.prototype.toString.call((obj)[e]) === '[object Object]'))
276
+ ? (obj)[e]
277
+ : {} as any,
278
+ path,
279
+ value
280
+ );
281
+ }
282
+ } else if (obj && path[0]) {
283
+ (obj)[path[0] as keyof T] = value;
284
+ }
285
+ }
286
+
287
+ /**
288
+ * Title case (or capitalize) first char of a string, for example "hello world" will become "Hello world"
289
+ * Change the string to be title case on the complete sentence (upper case first char of each word while changing everything else to lower case)
290
+ * @param inputStr
291
+ * @returns string
292
+ */
293
+ export function titleCase(inputStr: string, shouldTitleCaseEveryWords = false): string {
294
+ if (typeof inputStr === 'string') {
295
+ if (shouldTitleCaseEveryWords) {
296
+ return inputStr.replace(/\w\S*/g, (outputStr) => {
297
+ return outputStr.charAt(0).toUpperCase() + outputStr.substring(1).toLowerCase();
298
+ });
299
+ }
300
+ return inputStr.charAt(0).toUpperCase() + inputStr.slice(1);
301
+ }
302
+ return inputStr;
303
+ }
304
+
305
+ /**
306
+ * Converts a string to camel case (camelCase), for example "hello-world" (or "hellow world") will become "helloWorld"
307
+ * @param inputStr the string to convert
308
+ * @return the string in camel case
309
+ */
310
+ export function toCamelCase(inputStr: string): string {
311
+ if (typeof inputStr === 'string') {
312
+ return inputStr.replace(/(?:^\w|[A-Z]|\b\w|[\s+\-_\/])/g, (match: string, offset: number) => {
313
+ // remove white space or hypens or underscores
314
+ if (/[\s+\-_\/]/.test(match)) {
315
+ return '';
316
+ }
317
+
318
+ return offset === 0 ? match.toLowerCase() : match.toUpperCase();
319
+ });
320
+ }
321
+ return inputStr;
322
+ }
323
+
324
+ /**
325
+ * Converts a string to kebab (hypen) case, for example "helloWorld" will become "hello-world"
326
+ * @param str the string to convert
327
+ * @return the string in kebab case
328
+ */
329
+ export function toKebabCase(inputStr: string): string {
330
+ if (typeof inputStr === 'string') {
331
+ return toCamelCase(inputStr).replace(/([A-Z])/g, '-$1').toLowerCase();
332
+ }
333
+ return inputStr;
334
+ }
335
+
336
+ /**
337
+ * Converts a camelCase or kebab-case string to a sentence case, for example "helloWorld" will become "Hello World" and "hello-world" will become "Hello world"
338
+ * @param str the string to convert
339
+ * @return the string in kebab case
340
+ */
341
+ export function toSentenceCase(inputStr: string): string {
342
+ if (typeof inputStr === 'string') {
343
+ const result = inputStr.replace(/([A-Z])|(\-)/g, ' $1').replace(/\s+/g, ' ').trim();
344
+ return result.charAt(0).toUpperCase() + result.slice(1);
345
+ }
346
+ return inputStr;
347
+ }
348
+
349
+ /**
350
+ * Converts a string from camelCase to snake_case (underscore) case
351
+ * @param str the string to convert
352
+ * @return the string in kebab case
353
+ */
354
+ export function toSnakeCase(inputStr: string): string {
355
+ if (typeof inputStr === 'string') {
356
+ return toCamelCase(inputStr).replace(/([A-Z])/g, '_$1').toLowerCase();
357
+ }
358
+ return inputStr;
359
+ }
360
+
361
+ /**
362
+ * Takes an input array and makes sure the array has unique values by removing duplicates
363
+ * @param array input with possible duplicates
364
+ * @return array output without duplicates
365
+ */
366
+ export function uniqueArray<T = any>(arr: T[]): T[] {
367
+ if (Array.isArray(arr) && arr.length > 0) {
368
+ return arr.filter((item: T, index: number) => {
369
+ return arr.indexOf(item) >= index;
370
+ });
371
+ }
372
+ return arr;
373
+ }
374
+
375
+ /**
376
+ * Takes an input array of objects and makes sure the array has unique object values by removing duplicates
377
+ * it will loop through the array using a property name (or "id" when is not provided) to compare uniqueness
378
+ * @param array input with possible duplicates
379
+ * @param propertyName defaults to "id"
380
+ * @return array output without duplicates
381
+ */
382
+ export function uniqueObjectArray(arr: any[], propertyName = 'id'): any[] {
383
+ if (Array.isArray(arr) && arr.length > 0) {
384
+ const result = [];
385
+ const map = new Map();
386
+
387
+ for (const item of arr) {
388
+ if (item && !map.has(item[propertyName])) {
389
+ map.set(item[propertyName], true); // set any value to Map
390
+ result.push({
391
+ id: item[propertyName],
392
+ name: item.name
393
+ });
394
+ }
395
+ }
396
+ return result;
397
+ }
398
+ return arr;
399
+ }