forked from chrisweb/chrisweb-utilities.js
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathutilities.ts
799 lines (585 loc) · 21 KB
/
utilities.ts
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
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
'use strict';
var errorLogger;
export module utilities {
export const version: string = '0.0.4';
export const logFontColor: string = 'default';
export const logBackgroundColor: string = 'default';
export const logSpecial: boolean = false;
export const logVerbose: boolean = true;
/**
*
* html log
* create a div an insert the messages in div
* can be usefull on mobile if no other console is available
*
* @param {type} logObjects
* @param {type} logObjectsLength
* @param {type} logFontColor
* @param {type} logBackgroundColor
* @returns {undefined}
*/
export function htmlLog(logObjects: Array<string>, logObjectsLength: number, logFontColor: string, logBackgroundColor: string) {
// TODO: fix: seems that if logging starts before "domload" some
// messages get lost
if (document.getElementById('log') === null) {
const logDiv = document.createElement('div');
logDiv.id = 'log';
logDiv.style.cssText = 'position: absolute; overflow: scroll; left: 0; bottom: 0; padding: 0; margin: 0; border: 0; z-index: 999999; width: 100%; height: 20%; background-color: #fff;';
document.body.appendChild(logDiv);
}
for (let i = 0; i < logObjectsLength; i++) {
const logSpan = document.createElement('span');
logSpan.style.cssText = 'color: #' + logFontColor + '; background-color: #' + logBackgroundColor + ';';
const spanContent = document.createTextNode(logObjects[i]);
logSpan.appendChild(spanContent);
document.getElementById('log')!.appendChild(logSpan);
const brElement = document.createElement('br');
document.getElementById('log')!.appendChild(brElement);
}
};
/**
*
* file log
* nodejs logging to file
*
* @param {type} logObjects
* @param {type} logObjectsLength
* @param {type} logFontColor
* @returns {undefined}
*/
export function fileLog(logObjects: Array<string>, logObjectsLength: number, logFontColor: string): void {
try {
const winston = require('winston');
for (let i = 0; i < logObjectsLength; i++) {
switch (logFontColor) {
case 'red':
winston.error(logObjects[i]);
break;
case 'yellow':
winston.warn(logObjects[i]);
break;
default:
winston.info(logObjects[i]);
}
}
} catch (e) {
// winston is not installed
}
};
/**
*
* log messages
*
* @returns {Boolean}
*/
export function log(...args: Array<any>): void {
// is console defined, some older IEs don't have a console
if (typeof (console) === 'undefined') {
return;
}
// extract options and get objects to log
const logArguments = handleLogArguments(args);
const logObjects = logArguments.objects;
const logFontColor = logArguments.fontColor;
const logBackgroundColor = logArguments.backgroundColor;
const logObjectsLength = logObjects.length;
// nodejs or browser mode
if (typeof (window) === 'undefined') {
if (typeof (utilities.logVerbose) !== 'undefined'
&& utilities.logVerbose === true) {
// get background and fontColor codes
const color = getServerColors(logFontColor, logBackgroundColor);
// log each object
for (let i = 0; i < logObjectsLength; i++) {
if (typeof (logObjects[i]) === 'string') {
console.log(color.background + color.font + logObjects[i] + color.reset);
} else {
console.log(logObjects[i]);
}
};
}
// log to file if logSpecial is enabled or if the fontColor is red
if ((typeof (utilities.logSpecial) !== 'undefined' && utilities.logSpecial === true) || logFontColor === 'red') {
fileLog(logObjects, logObjectsLength, logFontColor);
}
} else {
// get background and fontColor codes
const color = getClientColors(logFontColor, logBackgroundColor);
if (typeof (utilities.logVerbose) !== 'undefined'
&& utilities.logVerbose === true) {
// log each object
for (var i = 0; i < logObjectsLength; i++) {
if (typeof (logObjects[i]) === 'string') {
console.log('%c' + logObjects[i], 'background: #' + color.background + '; color: #' + color.font);
} else {
console.log(logObjects[i]);
}
};
}
// log to html if logSpecial is enabled
if (typeof (utilities.logSpecial) !== 'undefined'
&& utilities.logSpecial === true) {
htmlLog(logObjects, logObjectsLength, color.font, color.background);
}
}
};
/**
*
* get the client side (browser) colors
*
* @param {type} logFontColor
* @param {type} logBackgroundColor
* @returns {_L16.getClientColors.Anonym$2}
*/
function getClientColors(logFontColor: string, logBackgroundColor: string): {font: string, background: string} {
const colors: {[color: string]: string} = {
red: 'FF0000',
green: '00FF00',
yellow: 'FFFF00',
blue: '0000FF',
magenta: 'FF00FF',
cyan: '00FFFF',
white: 'FFFFFF',
black: '000000'
};
let fontColor;
let backgroundColor;
// font color
if (typeof (logFontColor) === 'undefined' || logFontColor === 'default') {
fontColor = colors['black'];
} else {
if (typeof (colors[logFontColor]) !== 'undefined') {
fontColor = colors[logFontColor];
} else {
throw 'unknown fontColor in utilities console log';
}
}
// background color
if (typeof (logBackgroundColor) === 'undefined' || logBackgroundColor === 'default') {
backgroundColor = colors['white'];
} else {
if (typeof (colors[logBackgroundColor]) !== 'undefined') {
backgroundColor = colors[logBackgroundColor];
} else {
throw 'unknown fontColor in utilities console log';
}
}
return { font: fontColor, background: backgroundColor };
};
/**
*
* get the colors for the backend (server) console
*
* @param {type} logFontColor
* @param {type} logBackgroundColor
* @returns {_L16.getServerColors.Anonym$2}
*/
function getServerColors(logFontColor: string, logBackgroundColor: string): {font: string, background: string, reset: string} {
const backgroundColors: {[color: string]: string} = {
black: '\u001b[40m',
red: '\u001b[41m',
green: '\u001b[42m',
yellow: '\u001b[43m',
blue: '\u001b[44m',
magenta: '\u001b[45m',
cyan: '\u001b[46m',
white: '\u001b[47m'
};
const foregroundColors: {[color: string]: string} = {
black: '\u001b[30m',
red: '\u001b[31m',
green: '\u001b[32m',
yellow: '\u001b[33m',
blue: '\u001b[34m',
magenta: '\u001b[35m',
cyan: '\u001b[36m',
white: '\u001b[37m'
};
let fontColor;
let backgroundColor;
// font color
if (typeof (logFontColor) === 'undefined' || logFontColor === 'default') {
fontColor = foregroundColors['white'];
} else {
if (typeof (foregroundColors[logFontColor]) !== 'undefined') {
fontColor = foregroundColors[logFontColor];
} else {
throw 'unknown font color in utilities console log';
}
}
// background color
if (typeof (logBackgroundColor) === 'undefined' || logBackgroundColor === 'default') {
backgroundColor = backgroundColors['black'];
} else {
if (typeof (backgroundColors[logBackgroundColor]) !== 'undefined') {
backgroundColor = backgroundColors[logBackgroundColor];
} else {
throw 'unknown background color in utilities console log';
}
}
return { font: fontColor, background: backgroundColor, reset: '\u001b[0m' };
};
/**
*
* handle log arguments
* extract the color infos from the arguments to log
*
* @param {type} logArguments
* @returns {_L16.handleLogArguments.Anonym$2}
*/
function handleLogArguments(logArguments: Array<string>): {objects: Array<string>, fontColor: string, backgroundColor: string} {
const logObjects: Array<string> = [];
let logFontColor = utilities.logFontColor;
let logBackgroundColor = utilities.logBackgroundColor;
const argumentsLength = logArguments.length;
for (let i = 0; i < argumentsLength; i++) {
var argument = logArguments[i];
if (typeof (argument) === 'string') {
if (argument.substr(0, 10) === 'fontColor:') {
logFontColor = argument.substr(10, argument.length).trim();
} else if (argument.substr(0, 16) === 'backgroundColor:') {
logBackgroundColor = argument.substr(16, argument.length).trim();
} else {
logObjects.push(argument);
}
} else {
logObjects.push(argument);
}
}
return { objects: logObjects, fontColor: logFontColor, backgroundColor: logBackgroundColor };
};
/**
*
* returns the timestamp of right now for browser that dont support
* es5 Date.now
*
* @returns {Number}
*/
function getTimestamp(): number {
return new Date().getTime();
};
/**
*
* extracts html elements (and their content) from strings
*
* @param {string} text
* @param {boolean} removeTextBetweenTags
* @returns {string}
*/
export function removeElements(text: string, removeTextBetweenTags: boolean = false): string {
if (removeTextBetweenTags === false) {
// replace single tags
text = text.replace(/<[^>]*>?/g, '');
} else {
// replace all tags and whats inside
text = text.replace(/<[^>]*>[^>]*<\/[^>]*>?/g, '');
// replace single tags
text = text.replace(/<[^>]*>?/g, '');
}
return text;
};
/**
*
* unescapes a string and uses removeElements to ensure the string does not contain html elements
*
* @param {string} rawText
* @returns {string}
*/
export function safeUnescape(rawText: string, extendedEscape?: boolean, myEscapeList?: { [key: string]: string }): string {
const unEscapeList: {[key: string]: string} = {
// usually you would just escape (unescape) characters that get
// used in (x)html
'&': '&',
'<': '<',
'>': '>',
'"': '"',
''': "'",
'`': '`'
}
// by default also use extended list
if (extendedEscape === undefined || extendedEscape === true) {
const unEscapeExtendedList: {[key: string]: string} = {
// but in the case where everything has been encoded lets decode these too
'‘': '‘',
'’': '’',
'‚': '‚',
'“': '“',
'”': '”',
'„': '„',
'†': '†',
'‡': '‡',
'‰': '‰',
'‹': '‹',
'›': '›',
'–': '-',
'—': '—',
' ': ' ',
'¡': '¡',
'¢': '¢',
'£': '£',
'¤': '¤',
'¥': '¥',
'¦': '¦',
'&brkbar;': '¦',
'§': '§',
'¨': '¨',
'¨': '¨',
'©': '©',
'ª': 'ª',
'«': '«',
'¬': '¬',
'­': ' ',
'®': '®',
'¯': '¯',
'&hibar;': '¯',
'°': '°',
'±': '±',
'²': '²',
'³': '³',
'´': '´',
'µ': 'µ',
'¶': '¶',
'·': '·',
'¸': '¸',
'¹': '¹',
'º': 'º',
'»': '»',
'¼': '¼',
'½': '½',
'¾': '¾',
'¿': '¿'
};
for (let key in unEscapeExtendedList) {
unEscapeList[key] = unEscapeExtendedList[key];
}
}
if (myEscapeList !== undefined) {
for (let key in myEscapeList) {
unEscapeList[key] = myEscapeList[key];
}
}
const escaper = function (match: string) {
return unEscapeList[match];
};
// regexes for identifying a key that needs to be escaped
const unEscapeKeys = Object.keys(unEscapeList);
const source = '(?:' + unEscapeKeys.join('|') + ')';
const testRegexp = RegExp(source);
const replaceRegexp = RegExp(source, 'g');
rawText = rawText == null ? '' : '' + rawText;
const unescapedText = testRegexp.test(rawText) ? rawText.replace(replaceRegexp, escaper) : rawText;
const text = removeElements(unescapedText, false);
return text;
};
/**
*
* returns a universally unique identifier
*
* @returns {unresolved}
*/
export function generateUUID(): string {
// http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript
// http://www.ietf.org/rfc/rfc4122.txt
const s: Array<any> = [];
const hexDigits = "0123456789abcdef";
for (let i = 0; i < 36; i++) {
s[i] = hexDigits.substr(Math.floor(Math.random() * 0x10), 1);
}
s[14] = "4"; // bits 12-15 of the time_hi_and_version field to 0010
s[19] = hexDigits.substr((s[19] & 0x3) | 0x8, 1); // bits 6-7 of the clock_seq_hi_and_reserved to 01
s[8] = s[13] = s[18] = s[23] = "-";
var uuid = s.join("");
return uuid;
};
/**
*
* filters a string
* removes everything that is a not an alpha or numeric character, plus
* the characters if any got specified as second argument
*
* @param {type} inputString
* @param {type} specialCharacters
* @returns {Boolean}
*/
export function filterAlphaNumericPlus(inputString: string, specialCharacters: string): string | boolean {
if (typeof (inputString) === 'string' && inputString.length > 0) {
let outputString;
if (specialCharacters !== undefined) {
const regex = RegExp('[^a-z0-9' + specialCharacters + ']', 'gi');
outputString = inputString.replace(regex, '');
} else {
outputString = inputString.replace(/[^a-z0-9]/gi, '');
}
return outputString;
}
return false;
};
/**
*
* decode uri
*
* @param {type} uri
* @returns {unresolved}
*/
export function decodeUri(uri: string): string {
const additionToSpace = '/\+/g'; // replace addition symbol with a space
return decodeURIComponent(uri.replace(additionToSpace, ' '));
};
/**
*
* encode uri
*
* @param {type} uri
* @returns {unresolved}
*/
export function encodeUri(uri: string): string {
return encodeURIComponent(uri);
};
/**
*
* find and remove an array entry
*
* @param {type} array
* @param {type} removeMe
* @returns {undefined}
*/
export function arrayRemove<T>(array: Array<T>, removeMe: T): Array<T> {
const index = array.indexOf(removeMe);
if (index > -1) {
array.splice(index, 1);
}
return array;
};
/**
*
* capitalise first letter of a string
*
* @param string string
* @returns {unresolved}
*/
export function capitaliseFirstLetter(string: string): string {
return string.charAt(0).toUpperCase() + string.slice(1);
};
/**
*
* get url parameters
*
* @param string query
* @returns {_L16.utilities@call;decodeUri|Boolean}
*/
export function getUrlParameters(query: string): object {
if (query === undefined) {
if (window !== undefined) {
query = window.location.search.substring(1);
} else {
throw 'you must provide a query to parse';
}
}
const search = /([^&=]+)=?([^&]*)/g;
const urlParams: {[key: string]: string} = {};
const parameters = search.exec(query);
if (!!parameters) {
for (let i = 0; i <= parameters.length; i++) {
const parameter = parameters[i];
urlParams[decodeUri(parameter[1])] = decodeUri(parameter[2]);
}
}
return urlParams;
};
/**
*
* does a string contain another string
*
* @param {type} string
* @param {type} contains
* @returns {Boolean}
*/
export function stringContains(string: string, contains: string): boolean {
if (typeof string !== 'string') {
throw 'input is not a string';
}
if (string.indexOf(contains) > -1) {
return true;
} else {
return false;
}
};
/**
*
* get the index of a substring in a string with optional nth time it occurs
*
* @param {type} string
* @param {type} substring
* @param {type} nthTime
* @returns {unresolved}
*/
export function getSubstringIndex(string: string, substring: string, nthTime: number): number {
let times = 0;
let index = 0;
if (nthTime === 0) {
nthTime = 1;
}
while (times < nthTime && index !== -1) {
index = string.indexOf(substring, index + 1);
times++;
}
return index;
};
/**
* does the script run on the server
*/
export function isServer(): boolean {
if (typeof (global) === 'object') {
return true;
} else {
return false;
}
};
/**
* does the script run in a client
*/
export function isClient(): boolean {
return !isServer();
};
/**
* replace the placeholder(s) with some value
*/
export function replacePlaceholders(input: string, replacements: {[key: string]: string}): string {
var output = input;
if (typeof input === 'string' && typeof replacements === 'object') {
output = input.replace(/\b\w+?\b/g, function replacePlaceHolder(placeholder) {
return Object.prototype.hasOwnProperty.call(replacements, placeholder) ? replacements[placeholder] : placeholder;
});
}
return output;
};
/**
* URL utility to get a parameter by name from an URL
*/
export function getUrlParameterByName(name: string, url?: string): string|null {
if (!url) {
url = window.location.href;
}
name = name.replace(/[\[\]]/g, "\\$&");
const regex = new RegExp("[?&]" + name + "(=([^&#]*)|&|#|$)");
const results = regex.exec(url);
if (!results) {
return null;
}
if (!results[2]) {
return '';
}
return decodeURIComponent(results[2].replace(/\+/g, " "));
}
/**
* URL utility to replace a given parameter
*/
export function replaceUrlParameter(url: string, paramName: string, paramValue: string): string {
const pattern = new RegExp('\\b(' + paramName + '=).*?(&|$)');
if (url.search(pattern) >= 0) {
return url.replace(pattern, '$1' + paramValue + '$2');
}
return url + (url.indexOf('?') > 0 ? '&' : '?') + paramName + '=' + paramValue;
}
};
export default utilities;