/
index.js
746 lines (659 loc) · 15.9 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
/**
* Author: Ganesh Rathinavel
* License: MIT
* Repo URL: https://github.com/ganeshrvel/npm-nice-utils
* Contacts: ganeshrvel@outlook.com
*/
/**
* Intersect two arrays
*
* @param array1
* @param array2
* @returns {array}
*/
export const arrayIntersection = (array1, array2) => {
return array1.filter(element => array2.includes(element));
};
/**
* Change the url hash in the address bar and push the same into the browser history
*
* @param param
*/
export const changeURLHash = (param = '') => {
if (undefinedOrNull(window)) {
return null;
}
if (undefinedOrNull(param)) {
param = '';
} else {
param = '#' + param;
}
let scrollV = 0;
let scrollH = 0;
let loc = window.location;
if ('pushState' in history) {
history.pushState('', document.title, loc.pathname + loc.search + param);
} else {
scrollV = document.body.scrollTop;
scrollH = document.body.scrollLeft;
loc.hash = param;
document.body.scrollTop = scrollV;
document.body.scrollLeft = scrollH;
}
};
/**
* Sanitizes the html tags by escaping the html tags
*
* @param str
* @returns {{escape: string, unescape: string}}
*/
export const htmlSanitize = (str = '') => {
return {
escape: str
.replace(/&/g, '&')
.replace(/"/g, '"')
.replace(/'/g, ''')
.replace(/</g, '<')
.replace(/>/g, '>'),
unescape: str
.replace(/"/g, '"')
.replace(/'/g, "'")
.replace(/</g, '<')
.replace(/>/g, '>')
.replace(/&/g, '&')
};
};
/**
* Checks whether the input is an Array
*
* @param arr
* @returns {boolean}
*/
export const isArray = arr => {
if (typeof Array.isArray === 'undefined') {
Array.isArray = arr => {
return Object.prototype.toString.call(arr) === '[object Array]';
};
}
return Array.isArray(arr);
};
/**
* Checks whether the inputted arrays are equal
*
* @param array1
* @param array2
* @returns {boolean}
*/
export const isArrayEqual = (array1, array2) => {
return (
array1.length === array2.length &&
array1.sort().every((value, index) => {
return value === array2.sort()[index];
})
);
};
/**
* Wait for a DOM element to load.
*
* @param selector: eg: input#id
* @param time, time interval
* @returns Promise
*/
export const isElementLoaded = (selector, time = 500) => {
if (undefinedOrNull(window)) {
return null;
}
// eslint-disable-next-line compat/compat
return new Promise((resolve, reject) => {
if (typeof selector === 'undefined' || selector === null) {
return reject(null);
}
let _interval = setInterval(() => {
if (document.querySelector(selector) != null) {
clearInterval(_interval);
return resolve(document.querySelector(selector));
}
}, time);
});
};
/**
* Checks whether the given variable is a floating point
*
* @param n
* @returns {boolean}
*/
export const isFloat = n => {
if (typeof n !== 'number') {
return false;
}
return Number(n) === n && n % 1 !== 0;
};
/**
* Checks whether the given variable is a function
*
* @param fn
* @returns {boolean}
*/
export const isFunction = fn => {
return Object.prototype.toString.call(fn) === '[object Function]';
};
/**
* Wait for an image to load.
* @param src
* @returns {Promise}
*/
export const isImageLoaded = src => {
if (undefinedOrNull(window)) {
// eslint-disable-next-line compat/compat
return Promise.resolve(null);
}
// eslint-disable-next-line compat/compat
return new Promise(resolve => {
const img = new Image();
img.onload = () => resolve({ src: src, status: 'ok' });
img.onerror = () => resolve({ src: src, status: 'error' });
img.src = src;
});
};
/**
* Checks whether the given variable is an integer
*
* @param n
* @returns {boolean}
*/
export const isInt = n => {
if (typeof n !== 'number') {
return false;
}
return Number(n) === n && n % 1 === 0;
};
/**
* Checks whether the device is iOS
*
* @returns {boolean}
*/
export const isIos = () => {
return /iPad|iPhone|iPod/.test(navigator.userAgent) && !window.MSStream;
};
/**
* Checks whether the variable is a JSON Object
*
* @param obj
* @returns {boolean}
*/
export const isJson = obj => {
if (typeof obj !== 'string') {
obj = JSON.stringify(obj);
}
try {
const o = JSON.parse(obj);
if (o && typeof o === 'object') {
return true;
}
} catch (e) {
return false;
}
return false;
};
/**
* Checks whether the given variable is a number of not
*
* @param n
* @returns {boolean}
*/
export const isNumber = n => {
return typeof n === 'number';
};
/**
* Checks whether the input variable is an Object
*
* @param obj
* @returns {boolean}
*/
export const isObject = obj => {
if (obj === null) {
return false;
}
return typeof obj === 'function' || typeof obj === 'object';
};
/**
* Checks whether the input variable is an String
*
* @param str
* @returns {boolean}
*/
export const isString = str => {
return (
typeof str === 'string' ||
(!!str &&
typeof str === 'object' &&
Object.prototype.toString.call(str) === '[object String]')
);
};
/**
* Checks whether the device is touch enabled
*
* @returns {boolean}
*/
export const isTouchDevice = () => {
if (undefinedOrNull(window)) {
return false;
}
return 'ontouchstart' in window || navigator.msMaxTouchPoints > 0;
};
/**
* Get the actual width of an element; It takes the styles of its children into consideration;
* Total width: width + margin - padding + border
* @param selector => id or class name
* @returns {*}
*/
export const netElementWidth = selector => {
if (
undefinedOrNull(selector) ||
undefinedOrNull(document) ||
undefinedOrNull(window)
) {
return null;
}
const elem = document.querySelectorAll(selector);
let total = 0;
elem &&
Object.keys(elem).length > 0 &&
Object.keys(elem).forEach(i => {
const style = elem[i].currentStyle || window.getComputedStyle(elem[i]);
const width = elem[i].offsetWidth;
const margin =
parseFloat(style.marginLeft) + parseFloat(style.marginRight);
const padding =
parseFloat(style.paddingLeft) + parseFloat(style.paddingRight);
const border =
parseFloat(style.borderLeftWidth) + parseFloat(style.borderRightWidth);
total += width + margin - padding + border;
});
return total;
};
/**
* Converts the byte size into human readable format
*
* @param a
* @param b
* @returns {string}
*/
export const niceBytes = (a, b) => {
if (a === 0) {
return '0 Bytes';
}
const c = 1024;
const d = b || 2;
const e = ['Bytes', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];
const f = Math.floor(Math.log(a) / Math.log(c));
return `${parseFloat((a / Math.pow(c, f)).toFixed(d))} ${e[f]}`; // eslint-disable-line no-restricted-properties
};
/**
* Return numeric value from the input string
* @param number
* @param allowDecimal
* @param pattern
* @returns {*}
*/
export const onlyNumbers = (
number = null,
allowDecimal = false,
pattern = /[^1-9]/g
) => {
if (!isNaN(number)) {
return number;
}
if (allowDecimal) {
pattern = /[^1-9.]/g;
}
return number.replace(new RegExp(pattern, 'gi'), '');
};
/**
* Find the percentage of two numbers
*
* @param current
* @param total
* @returns {number}
*/
export const percentage = (current, total) => {
return parseInt((current / total) * 100, 10);
};
/**
* Quick hash for generating a unique id
*
* @param str
* @returns {number}
*/
export const quickHash = str => {
let hash = 0;
let i;
let chr;
if (str.length === 0) {
return hash;
}
for (i = 0; i < str.length; i += 1) {
chr = str.charCodeAt(i);
hash = (hash << 5) - hash + chr; // eslint-disable-line no-bitwise
hash |= 0; // eslint-disable-line no-bitwise
}
return hash;
};
/**
* Generates a lengthy random number
* @returns {number}
*/
export const randomNumber = () => {
return Math.floor(Math.random() * Date.now()) + Date.now();
};
/**
* Replace all occurrences of a sub-string
* @param str
* @param find
* @param replace
* @returns {string}
*/
export const replaceAll = (str, find, replace) => {
return str.replace(
new RegExp(find.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&'), 'gi'),
replace
);
};
/**
* Replace the string with matching patterns
*
* @param str
* @param findArray
* @param replaceArray
* @returns {string}
*/
export const replaceBulk = (str, findArray, replaceArray) => {
let i;
let regex = [];
const map = {};
for (i = 0; i < findArray.length; i += 1) {
regex.push(findArray[i].replace(/([-[\]{}()*+?.\\^$|#,])/g, '\\$1'));
map[findArray[i]] = replaceArray[i];
}
regex = regex.join('|');
return str.replace(new RegExp(regex, 'g'), matched => {
return map[matched];
});
};
/**
* Strip a character beginning and end of the string
*
* @param string
* @param search
* @returns {string}
*/
export const rtrim = (string, search = '') => {
string = string.toString();
if (typeof string === 'undefined' || string === null) {
return '';
}
if (search === '') {
return string.trim();
}
const regex = new RegExp('^' + search + '+|' + search + '+$', 'g');
return string.replace(regex, '').trim();
};
/**
* Split a string into multiple lines
*
* @param str
* @returns {*}
*/
export const splitIntoLines = str => {
if (undefinedOrNull(str)) {
return null;
}
return str.toString().split(/(\r?\n)/g);
};
/**
* Spring trucate a given string
*
* @param str
* @param minChars
* @param ellipsis
* @returns {object}
*/
export const springTruncate = (str, minChars = 10, ellipsis = '...') => {
const _str = str;
const strLength = str.length;
if (strLength > minChars) {
const ellipsisLength = ellipsis.length;
if (ellipsisLength > minChars) {
return {
text: _str,
truncatedText: str.substr(strLength - minChars),
isTruncated: true
};
}
const count = -0.5 * (minChars - strLength - ellipsisLength);
const center = strLength / 2;
return {
text: _str,
truncatedText: `${str.substr(0, center - count)}${ellipsis}${str.substr(
strLength - center + count
)}`,
isTruncated: true
};
}
return {
text: _str,
truncatedText: str,
isTruncated: false
};
};
/**
* Strip HTML Tags from an input string
* @param input; string
* @param allowed; <img> or <span><body>
* @returns {string}
*/
export const stripTags = (input = '', allowed = '') => {
allowed = (
((allowed || '') + '').toLowerCase().match(/<[a-z][a-z0-9]*>/g) || []
).join('');
const tags = /<\/?([a-z][a-z0-9]*)\b[^>]*>/gi;
const commentsAndPhpTags = /<!--[\s\S]*?-->|<\?(?:php)?[\s\S]*?\?>/gi;
return input.replace(commentsAndPhpTags, '').replace(tags, ($0, $1) => {
return allowed.indexOf('<' + $1.toLowerCase() + '>') > -1 ? $0 : '';
});
};
/**
* Array to Object
* @param arr
* @returns {object}
*/
export const toObject = arr => {
if (undefinedOrNull(arr) || arr.length < 1) {
return {};
}
const k = {};
for (let i = 0; i < arr.length; ++i) {
if (arr[i] !== undefined) {
k[i] = arr[i];
}
}
return k;
};
/**
* Truncate a string
*
* @param str
* @param length
* @returns {string}
*/
export const truncate = (str, length) => {
const dots = str.length > length ? '...' : '';
return str.substring(0, length) + dots;
};
/**
* Checks whether a given variable is undefined or null
* @param obj
* @returns {boolean}
*/
export const undefinedOrNull = obj => {
return typeof obj === 'undefined' || obj === null;
};
/**
* Checks whether a given nested object or array is undefined or null
*
* @param mainObj: object or array
* @param key: string
* @returns {boolean}
*/
export const undefinedOrNullChained = (mainObj, key = null) => {
let _return = undefined;
if (undefinedOrNull(mainObj)) {
return _return;
}
if (
!key ||
(Object.prototype.toString.call(key) !== '[object String]' &&
key.trim() === '')
) {
return _return;
}
const keyArray = key.split('.');
if (!keyArray || keyArray.length < 1) {
return _return;
}
let temp = mainObj;
keyArray.map(a => {
if (typeof temp !== 'undefined') {
const _matches = a.match(/[^[\]]+(?=])/g);
if (_matches && _matches.length > 0) {
let aSplits = a.split('[')[0],
lTemp = temp[aSplits];
_matches.map(e => {
if (typeof lTemp !== 'undefined' && typeof lTemp[e] !== 'undefined') {
return (lTemp = lTemp[e]);
}
lTemp = undefined;
});
return (temp = lTemp);
} else if (typeof temp[a] !== 'undefined') {
return (temp = temp[a]);
}
}
temp = _return;
});
return typeof temp !== 'undefined' ? temp : _return;
};
/**
* Get/Manipulate URL, URI parameters or hashes.
*
* get: returns parameter(s) in a url as an object; if url is empty current url is considered; if param is empty all url parameters are returned as an object
* getUrlWithoutHash: strips hash and return url; if url is empty current url is considered;
* getHash: returns the hash value of an url as an object; if url is empty current url is considered;
* parseHash: parses and returns multiple hash values of an url as an object; if url is empty current url is considered; if param is empty all url parameters are returned as an object
* removeHash: remove hash from the address bar url
* getUrlPath: get url location pathname
*
* @param url
* @returns {*}
*/
export const urls = (url = '') => {
return {
get(param = '') {
const data = {};
if (undefinedOrNull(url) || url === '') {
if (undefinedOrNull(window)) {
return null;
}
url = window.location.href;
}
url = urls(url).getUrlWithoutHash();
url.replace(/[?&]+([^=&]+)=([^&]*)/gi, (m, key, value) => {
data[key] = decodeURI(value);
});
if (param === '') {
return data;
}
if (typeof data[param] === 'undefined') {
return null;
}
return data[param];
},
getUrlWithoutHash() {
if (undefinedOrNull(url) || url === '') {
if (undefinedOrNull(window)) {
return null;
}
return window.location.href.split('#')[0];
}
const hash = url.split('#')[0];
if (hash) {
return hash;
}
return null;
},
getHash() {
if (undefinedOrNull(url) || url === '') {
if (undefinedOrNull(window)) {
return null;
}
return location.hash.replace('#', '').trim();
}
const hash = url.split('#')[1];
if (hash) {
return hash;
}
return null;
},
parseHash(param = '') {
const _url = !undefinedOrNull(url) && url !== '' ? url : '';
const hash = urls(_url).getHash();
if (undefinedOrNull(hash) || hash === '') {
return null;
}
const pieces = hash.split('&');
const data = {};
let parts;
for (let i = 0; i < pieces.length; i += 1) {
parts = pieces[i].split('=');
if (parts.length < 2) {
parts.push('');
}
data[decodeURIComponent(parts[0])] = decodeURIComponent(parts[1]);
}
if (param === '') {
return data;
}
if (typeof data[param] === 'undefined') {
return null;
}
return data[param];
},
removeHash() {
if (undefinedOrNull(window)) {
return null;
}
window.location.replace('#');
},
getUrlPath() {
if (undefinedOrNull(window)) {
return null;
}
return window.location.pathname;
}
};
};
/**
* URL Sanitize
* Encodes and decodes url parameters
* @param str
* @returns {{encode: string, decode: string}}
*/
export const urlSanitize = (str = '') => {
if (undefinedOrNull(str)) {
str = '';
}
return {
encode: encodeURIComponent(str.replace(/\\\//g, '')).replace(/%20/g, '+'),
decode: decodeURIComponent(str.replace(/\+/g, '%20'))
};
};