-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlibrary_standard.js
3550 lines (3250 loc) · 130 KB
/
library_standard.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
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
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
*
* ############################################################################
* ############################# Our JS Library ############################
* ### Here we collect frequently used methods across our JS applications. ###
* ### (Some of them are generic javascript functions, some are for NodeJS) ###
* ############################################################################
*
* ########## Example usage: ##########
* const helpers = new PuvoxLibrary();
* console.log ( helpers.get_last_child_of_array(array) );
* console.log ( helpers.get_visitor_ip() );
* console.log ( helpers.telegram_send("hello world", "1234567890", "BOTKEY123:456789") );
* ... etc
*
*/
class PuvoxLibrary {
selfMain = this;
constructor(appName) {
this.setAppName(appName);
}
// ########## ARRAY ########## //
arrayValue(obj_arr, key, default_){
return (obj_arr && key in obj_arr ? obj_arr[key] : default_);
}
arrayValueLower(obj_arr, key, default_){
const val = this.arrayValue(obj_arr, key, default_);
return (val===null ? null : val.toLowerCase());
}
arrayValueUpper(obj_arr, key, default_){
const val = this.arrayValue(obj_arr, key, default_);
return (val===null ? null : val.toUpperCase());
}
stringToArray(str, splitChar){
var splitChar= splitChar || '|';
let parts = str.split(splitChar);
return parts;
}
arrayColumn(array, columnName) {
return array.map(function(value,index) {
return value[columnName];
})
}
arrayUnique(array, removeEmpties){
//let uniqueItems = [...new Set(items)]
let res = array.filter(function(item, pos) {
return array.indexOf(item) == pos;
});
return (removeEmpties ? this.arrayRemoveEmpty(res) : res);
}
arrayMerge(ar1,ar2){
return ar1.concat(ar2);
}
objectsArrayTill(arrayBlocks, key, value)
{
let newArr = this.isObject(arrayBlocks) ? {} : [];
for(let [key_1,obj_1] of Object.entries(arrayBlocks))
{
if (key in obj_1 && obj_1[key]===value)
{
break;
}
newArr[key_1] = obj_1;
}
return newArr;
}
arrayRemoveEmpty(array){ return array.filter(item => item); }
arrayLastMember(arr){ return arr[arr.length-1]; }
arrayLastItem(arr){ return this.arrayLastMember(arr); }
removeKeys(obj, keysArr){
let newObj ={};
for (let [key,val] of Object.entries(obj)){
if (!this.inArray(key,keysArr))
newObj[key]=val;
}
return newObj;
}
removeKeysExcept (obj, keysArr){
let newObj ={};
for (let [key,val] of Object.entries(obj)){
if (this.inArray(key,keysArr))
newObj[key]=val;
}
return newObj;
}
arrayDiff(source, comparedTo){
return source.filter(x => !comparedTo.includes(x));
}
arrayIntersect(source, comparedTo){
return source.filter(x => comparedTo.includes(x));
}
arrayDiffFull(o1,o2) {
const selfFunc = this;
const typeObject = function(o){
return typeof o === 'object';
};
const bothAreObjects = (o1,o2) =>{
return (typeObject(o1) && typeObject(o2));
};
const bothAreArrays = (o1,o2) =>{
return (this.isArray(o1) && this.isArray(o2));
};
const diff = function (o1, o2) {
const result = {};
// if first is item is not object
if (!typeObject(o1) && typeObject(o2)) {
return o2;
}
// if second is item is not object
else if (typeObject(o1) && !typeObject(o2)) {
return undefined;
}
// if they are equal
else if (Object.is(o1, o2)) {
return undefined;
} else if (bothAreArrays(o1,o2)){
return selfFunc.arrayDiff(o1,o2);
}
const keys = Object.keys(o2);
for (let i=0; i<keys.length; i++) {
const key = keys[i];
// if both are objects
if ( bothAreObjects(o1[key],o2[key])) {
// if equal, return nothing
if ( Object.is(o1[key], o2[key]) ) {
// do nothing
} else if (o1[key] === o2[key]) {
// do nothing
} else {
result[key] = diff(o1[key],o2[key]);
}
} else if (bothAreArrays(o1[key],o2[key])) {
result[key] = diff(o1[key],o2[key]);
} else if (o1[key] !== o2[key]) {
result[key] = o2[key];
} else {
// do nothing
}
}
return result;
};
return [
diff(o1,o2),
diff(o2,o1),
];
}
sortKeys (x, out = {}) {
for (const k of Object.keys (x).sort ()) {
out[k] = x[k]
}
return out
}
sortByValuesIntoArray(obj, ascending = true){
return Object.entries(obj).sort((a, b) => ascending ? a[1] - b[1] : b[1] - a[1]);
}
stringArrayToNumeric(arr){
let newArr = [];
for(let i=0; i<arr.length; i++){
newArr.push( parseFloat(arr[i]) );
}
return newArr;
}
stringToArrayToNumeric(arr){
return this.stringArrayToNumeric(this.stringToArray(arr));
}
objectCopy(obj){
return JSON.parse(JSON.stringify(obj));
}
// https://stackoverflow.com/a/44782052/2377343
cloneObjectDestructuve(orig){
return Object.assign(Object.create(Object.getPrototypeOf(orig)), orig);
}
// https://stackoverflow.com/a/41474987/2377343
cloneObjectWithPrototype(orig){
const clone = Object.assign( Object.create(orig), orig );
Object.setPrototypeOf( clone, Blah.prototype );
return clone;
}
getKeyByValue (object, value) {
const keys = Object.keys (object);
for (let i = 0; i < keys.length; i++) {
const key = keys[i];
if (object[key] === value) {
return key;
}
}
return undefined;
}
hasChildWithKeyValue (obj, targetKey, targetValue) {
const keys = Object.keys (obj);
for (let i = 0; i < keys.length; i++) {
const currentKey = keys[i];
const childMember = obj[currentKey];
const value = this.safeInteger (childMember, targetKey, undefined);
if (value === targetValue) {
return true;
}
}
return false;
}
trigger_on_load(callerr, onInteractionInsteadComplete)
{
var stage=stage || 1;
if (onInteractionInsteadComplete || true){
document.addEventListener('readystatechange', event => {
if (event.target.readyState === "interactive") { //same as: document.addEventListener("DOMContentLoaded"
callerr(); //"All HTML DOM elements are accessible"
}
});
}
else{
document.addEventListener('readystatechange', event => {
if (event.target.readyState === "complete") {
callerr(); //"Now external resources are loaded too, like css,src etc... "
}
});
}
}
// setTimeout( window[arguments.callee.name.toString() ], 500);
// lazyload images
imagesLazyLoad(el_tag){
jQuery(el_tag).each( function(){
// set the img src from data-src
jQuery( this ).attr( 'src', jQuery( this ).attr( 'data-src' ) );
}
);
}
move_to_top_in_parent(el_tag)
{
$(el_tag).each(function() {
$(this).parent().prepend(this);
});
}
//window.onload REPLACEMENT Both methods are used to achieve the same goal of attaching an event to an element.
// ttachEvent can only be used on older trident rendering engines ( IE5+ IE5-8*) and addEventListener is a W3 standard that is implemented in the majority of other browsers (FF, Webkit, Opera, IE9+).
// window.addEventListener ? window.addEventListener("load",yourFunction,false) : window.attachEvent && window.attachEvent("onload",yourFunction);
// Append Style/Script In Head
Append_To_Head2(elemntType, content){
// if provided conent is "link" or "inline codes"
var Is_Link = content.split(/\r\n|\r|\n/).length <= 1 && content.indexOf("/") > -1 && (content.substring(0, 4)=='http' || content.substring(0, 2)=='//' || content.substring(0, 2)=='./' || content.substring(0, 1)=='/' );
if(Is_Link){
//assign temporary id
var id= encodeURI( content.split('/').reverse()[0] ); //encodeURI(content.replace(/[\W_]+/g,"-"));
if (!document.getElementById(id)){
if (elemntType=='script') { var x=document.createElement('script');x.id=id; x.src=content; x.type='text/javascript'; }
else if (elemntType=='style'){ var x=document.createElement('link'); x.id=id; x.href=content; x.type='text/css'; x.rel = 'stylesheet'; }
}
}
else{
var x = document.createElement(elemntType);
if (elemntType=='script') { x.type='text/javascript'; x.innerHTML = content; }
else if (elemntType=='style'){ x.type='text/css'; if (x.styleSheet){ x.styleSheet.cssText=content; } else { x.appendChild(document.createTextNode(content)); } }
}
//append in head
(document.head || document.getElementsByTagName('head')[0]).appendChild(x);
}
Append_To_Head(elemntType, content) {
var Is_Link = content.split(/\r\n|\r|\n/).length <= 1 && content.indexOf("/") > -1 && (content.substring(0, 4) == 'http' || content.substring(0, 2) == '//' || content.substring(0, 2) == './' || content.substring(0, 1) == '/');
if (Is_Link) {
var id = encodeURI(content.replace(/[\W_]+/g,"-"));
if (!document.getElementById(id)) {
if (elemntType == 'script') {
var x = document.createElement('script');
x.id = id;
document.head.appendChild(x);
x.onload = function () {};
x.src = content;
} else if (elemntType == 'style') {
var x = document.createElement('link');
x.id = id;
x.href = content;
x.type = 'text/css';
x.rel = 'stylesheet';
document.head.appendChild(x);
}
}
} else {
var x = document.createElement(elemntType);
if (elemntType == 'script') {
x.type = 'text/javascript';
x.innerHTML = content;
} else if (elemntType == 'style') {
x.type = 'text/css';
if (x.styleSheet) {
x.styleSheet.cssText = content;
} else {
x.appendChild(document.createTextNode(content));
}
}
document.head.appendChild(x);
}
}
// loadScript
appendScript(url, callback, defer=false){
var script = document.createElement('script');
script.onload = (callback || function(){});
script.src = url;
if (defer)
script.defer = true;
document.head.appendChild(script);
}
appendScript2(url){
var script = document.createElement('script');
document.head.appendChild(script);
script.onload = function () { };
script.src = url;
}
blackground2(){
var innerDiv = document.createElement("div"); innerDiv.id = "my_black_backgr";
innerDiv.setAttribute("style", "background:black; height:4000px; left:0px; opacity:0.9; position:fixed; top:0px; width:100%; z-index:9990;");
var BODYYY = document.body; BODYYY.insertBefore(innerDiv, BODYYY.childNodes[0]);
}
getFileExtension(filename){
var ext = filename.split('.').pop();
return (ext===filename) ? '' : ext;
}
// stackoverflow -best foreach
forEach(collection, callback, scope) {
if (Object.prototype.toString.call(collection) === '[object Object]') {
for (var prop in collection) {
if (Object.prototype.hasOwnProperty.call(collection, prop)) {
callback.call(scope, collection[prop], prop, collection);
}
}
} else {
for (var i = 0, len = collection.length; i < len; i++) {
callback.call(scope, collection[i], i, collection);
}
}
}
// ################
sanitize(str){ return str.trim().replace( /[^a-zA-Z0-9_\-]/g, "_"); }
sanitize_key(str, use_dash){ return str.trim().toLowerCase().replace( /[^a-z0-9_\-]/g, (use_dash===true ? '_' : (use_dash ? use_dash :'')) ); } //same as wp
sanitize_key_dashed(str){ return this.sanitize_key(str, true).replace(/__/g,'_'); }
sanitize_variable_name(str) { return this.strip_non_word(str).replace(/-/g,"_"); }
sanitize_text(str, use_dash=false) { return str.trim().replace(/[^a-zA-Z0-9]+/g, (use_dash ? "_":"") ); }
//nonword
strip_non_word(str) { return str.replace(/[\W_]+/g,"-"); }
removeAllWhitespaces(content){ return content.replace(/\s/g,''); }
replaceAllOccurences (input, search, replacement) {
const splited = input.split (search);
const joined = splited.join (replacement);
return joined;
}
// ####################### TYPE ##############################
getVariableType(x) {
if (this.isInteger(x)) return "integer";
else if (this.isDecimal(x)) return "float";
else if (this.isBoolean(x)) return "boolean"; //at first, priority to bool, because of "true" and "false" strings
else if (this.isString(x)) return "string";
else if (this.isArray(x)) return "array";
else if (this.isObject(x)) return "object";
return typeof x;
}
isInteger(x) { return Number.isInteger(x); }
isNumeric(x) { return Number.isFinite(x); }
isDecimal(x) { return this.isNumeric(x) && (!isNaN(parseFloat(x))); } // avoid occasions like "1abc"
isBoolean(x) { return this.isBooleanReal(x) || (this.isString(x) && (x.toLowerCase() =="true" || x.toLowerCase() =="false")); }
isBooleanReal(x) { return x === true || x === false || toString.call(x) === '[object Boolean]'; }
isString(x) { return Object.prototype.toString.call(x) === "[object String]"; } // return (typeof content === 'string' || content instanceof String);
// https://stackoverflow.com/questions/8834126/
isObject(x) { return ( !Array.isArray(x) && Object.prototype.toString.call(x) !== '[object Array]' ) && ( (typeof x === 'object' && x !== null ) || ( (!!x) && (x.constructor === Object) ) || (typeof x === 'function' || typeof x === 'object' && !!x) ) ; }
// https://stackoverflow.com/questions/8511281/check-if-a-value-is-an-object-in-javascript
isJsonObject(data){
// doesnt work for string return data!="" && (data=={} || JSON.stringify(data)!='{}');
return false;
}
isArray(x) { return ( (!!x) && (x.constructor === Array) ) || (Array.isArray(x)); }
isSimpleVariableType(obj){ return this.isSimpleVariableTypeName(typeof obj); }
isSimpleVariableTypeName(typeName_){ return this.inArray( typeName_, [ "boolean", "integer", "float", "double", "decimal", "string"]); }
isNumericVariableType(obj){ return this.isNumericVariableTypeName(typeof obj); }
isNumericVariableTypeName(typeName_){ return this.inArray(typeName_, [ "integer", "float", "double", "decimal"]); }
stringToBoolean(string){
switch(string.toLowerCase().trim()){
case "true": case "yes": case "1": return true;
case "false": case "no": case "0": case null: return false;
default: return Boolean(string);
}
}
isException(e){
return e && e.stack && e.message;
}
IsJsonString (str) {
return this.isJsonEncodedObject(str);
try { JSON.parse(str); return true; } catch (e) { return false; }
}
is_object(variable){
return typeof variable === 'object' && variable !== null;
}
formItemsToJson(FormElement){
let formData = undefined;
try { formData = new FormData(FormElement);}
catch (e) {
const newForm = document.createElement('form');
newForm.appendChild(FormElement.cloneNode(true));
formData = new FormData(newForm);
}
const formDataEntries = formData.entries();
const handleChild = function (obj,keysArr,value){
let firstK = keysArr.shift();
firstK=firstK.replace(']','');
if (keysArr.length==0){
if (firstK=='') {
if (!Array.isArray(obj)) obj=[];
obj.push(value);
}
else obj[firstK] = value;
}
else{
if (firstK=='') obj.push(value);
else {
if ( ! ( firstK in obj) ) obj[firstK]={};
obj[firstK] = handleChild(obj[firstK],keysArr,value);
}
}
return obj;
};
let result = {};
for (const [key, value] of formDataEntries )
result= handleChild(result, key.split(/\[/), value);
return result;
}
renameKey (obj, keyFrom, keyTo) {
for (const key of Object.keys(obj)) {
obj[keyTo] = obj[keyFrom];
delete obj[keyFrom];
}
return obj;
}
renameSubKey (obj, keyFrom, keyTo, strict = false) {
for (const key of Object.keys(obj)) {
obj[key][keyTo] = strict ? obj[key][keyFrom] : (obj[key][keyFrom] || null);
delete obj[key][keyFrom];
}
return obj;
}
hasEmptyChild(obj){
let hasEmpty = false;
if(this.isObject(obj)) {
for (let [key,val] of Object.entries(obj)){
if (val === null || val === undefined){
hasEmpty = true;
}
}
}
return hasEmpty;
}
filterObject(obj, callback) {
return Object.fromEntries(Object.entries(obj).
filter(([key, val]) => callback(val, key)));
}
// #####################################$$$$$################
isBetween(a,b,c) { return a< b && b< c; }
isBetweenEq(a,b,c) { return a<=b && b<=c; }
startsWithWhiteSpace(content){
return (/^\s/).test(content);
}
trimOnlyFromEnd(content){
return content.replace(/\s*$/,"");
}
startsWith(content, what){
return content.startsWith(what);
}
startsWithArray(content,array){
array.forEach(function(val){
if (content.startsWith(val)) return true;
})
return false;
}
endsWith(content, what){
return content.endsWith(what);
}
endsWithArray(content,array){
array.forEach(function(val){
if (content.endsWith(val)) return true;
})
return false;
}
startLetters(str, amountOfLetters){
return str.substr(0, amountOfLetters);
}
endLetters(str, amountOfLetters){
return str.substr(str.length - amountOfLetters);
}
ConvertNumbToRoman(num){
num= num.replace('40','XXXX'); num= num.replace('39','XXXIX'); num= num.replace('38','XXXVIII'); num= num.replace('37','XXXVII');
num= num.replace('36','XXXVI'); num= num.replace('35','XXXV'); num= num.replace('34','XXXIV'); num= num.replace('33','XXXII');
num= num.replace('32','XXXII'); num= num.replace('31','XXXI'); num= num.replace('30','XXX'); num= num.replace('29','XXIX');
num= num.replace('28','XXVIII');num= num.replace('27','XXVII'); num= num.replace('26','XXVI'); num= num.replace('25','XXV');
num= num.replace('24','XXIV'); num= num.replace('23','XXIII'); num= num.replace('22','XXII'); num= num.replace('21','XXI');
num= num.replace('20','XX'); num= num.replace('19','XIX'); num= num.replace('18','XVIII'); num= num.replace('17','XVII');
num= num.replace('16','XVI'); num= num.replace('15','XV'); num= num.replace('14','XIV'); num= num.replace('13','XIII');
num= num.replace('12','XII'); num= num.replace('11','XI'); num= num.replace('10','X'); num= num.replace('9','IX');
num= num.replace('8','VIII'); num= num.replace('7','VII'); num= num.replace('6','VI'); num= num.replace('5','V');
num= num.replace('4','IV'); num= num.replace('3','III'); num= num.replace('2','II'); num= num.replace('1','I'); return num;
}
// encrypt decrypt: http://jsfiddle.net/kein1945/M9K2c/ | https://stackoverflow.com/questions/18279141/ | https://stackoverflow.com/questions/51531021/x
//to check whenever element is loaded
when_element_is_loaded(Id_or_class,functionname){
Id_or_class=Id_or_class.trim(); var eName = Id_or_class.substr(1); if('#'==Id_or_class.charAt(0)){var x=document.getElementById(eName);} else{var x=document.getElementsByClassName(eName)[0];}
if(x) { functionname(); } else { setTimeout(when_element_is_loaded, 100, Id_or_class, functionname); }
}
// set document title
SetTitlee(title) { document.getElementsByTagName('title')[0].innerHTML = title; }
setUrl(urlPath, title) {
var title= title || false;
window.history.pushState( ( title ? {"pageTitle":title} : ""),"", urlPath); //{"html":...,"pageTitle":....}
}
requestUri(url){
var url = url || location.href;
return url.replace(origin,'');
}
// check if key exists in array
ArrayKeyExistss(keyname,array) {
return typeof array[keyname] !== 'undefined';
}
hashtageChangeOnClick(e) {
function MyCallbackTemp (e)
{
var e = window.e || e; var t=e.target;
if (t.tagName !== 'A') return;
else{
var link=t.href;
if( link.indexOf('#') >-1) { //found hashtag
var hashtag= link.split('#')[1]; //var match = url.match(/#.*[?&]locale=([^&]+)(&|$)/); return(match ? match[1] : "");(^|\s)(#[a-z\d-]+)
var sanitized_link= link.replace( location.href.split('#')[0] ,"");
if(link.indexOf(location.href) >-1 || sanitized_link.charAt(0)=='#') { //if conains current link, or starts with #
location.hash=hashtag;
}
}
}
}
if (document.addEventListener) document.addEventListener('click', MyCallbackTemp, false);
else document.attachEvent('onclick', MyCallbackTemp);
}
capitalizeFirstLetter(string) {
return string.charAt(0).toUpperCase() + string.slice(1);
}
addQueryArg(name,value, url)
{
var url = url || location.href;
return url + (url.indexOf("?")<0 ? "?":"&") +escape(name)+"="+escape(value);
}
buildQueryString(params){
if (!params) return '';
return Object.entries(params)
.map(([key, value]) => {
return `${key}=${encodeURIComponent(value)}`;
})
.join('&');
}
// find home url (in wordpress)
wpHomeUrl (){
var matches = /(href|src)\=\"(.*?)wp-content\//.exec(document.getElementsByTagName('head')[0].innerHTML);
if (typeof matches !== 'undefined' && matches != null && matches.length > 1 ){
homeURL = matches[2];
}
}
LoadYoutubeApi(callback)
{
// This code loads the IFrame Player API code asynchronously.
var tag = document.createElement('script');
tag.src = "https://www.youtube.com/iframe_api";
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
window.onYouTubeIframeAPIReady= function(){
callback();
};
}
argvsString(){ return process.argv[2]; }
argvsArray(){ return process.argv.slice(2); }
argvs(){
let argvs= this.argvsArray();
let KeyValues= {};
for (let i=0; i<argvs.length; i++){
let argumentString = argvs[i]; // each argument
let pair = {};
if ( argumentString.includes('=') ){
pair = this.parseQuery(argumentString);
} else {
pair[argumentString] = undefined;
}
let pairKey= Object.keys(pair)[0];
// if member already exists (i.e: cli key1=val1 key2=val2 key1=xyz..)
if (pairKey in KeyValues){
// if not array yet
if (!Array.isArray(KeyValues[pairKey]))
{
KeyValues[pairKey] = [ KeyValues[pairKey], pair[pairKey]];
}
// if already array-ed
else {
KeyValues[pairKey] = KeyValues[pairKey].concat([pair[pairKey]]);
}
} else {
KeyValues = Object.assign (KeyValues, pair);
}
}
return KeyValues;
}
argv(which, def = undefined){
let KeyValues= this.argvs();
return (which in KeyValues ? KeyValues[which] : def);
}
argvIsSet(which){
return this.inArray(which, this.argvsArray()) || this.argv(which)!=undefined;
}
parseQuery(queryString) {
let query = {};
let pairs = (queryString[0] === '?' ? queryString.substr(1) : queryString).split('&');
for (let i = 0; i < pairs.length; i++) {
let pair = pairs[i].split('=');
let p2 =decodeURIComponent(pair[1] || '');
try {
p2=JSON.parse(p2);
}
catch(ex){
p2=p2;
}
query[decodeURIComponent(pair[0])] = p2;
}
return query;
}
//https://stackoverflow.com/questions/123999/how-can-i-tell-if-a-dom-element-is-visible-in-the-current-viewport
// $(window).on('DOMContentLoaded load resize scroll', handler);
//function myHandler(el) {
// var visible = isElementInViewport(el);
//}
invertDictionary(obj) {
const newObj = {};
Object.keys(obj).map (k=>newObj[obj[k]]=k);
return newObj;
}
isElementInViewport (el) {
// Special bonus for those using jQuery
if (typeof jQuery === "function" && el instanceof jQuery) {
el = el[0];
}
var rect = el.getBoundingClientRect();
return (
rect.top >= 0 &&
rect.left >= 0 &&
rect.bottom <= (window.innerHeight || document.documentElement.clientHeight) && /* or $(window).height() */
rect.right <= (window.innerWidth || document.documentElement.clientWidth) /* or $(window).width() */
);
}
MakeIframeFullHeight(iframeElement, cycling, overwrite_margin){
cycling= cycling || false;
overwrite_margin= overwrite_margin || false;
iframeElement.style.width = "100%";
var ifrD = iframeElement.contentDocument || iframeElement.contentWindow.document;
var mHeight = parseInt( window.getComputedStyle( ifrD.documentElement).height ); // Math.max( ifrD.body.scrollHeight, .. offsetHeight, ....clientHeight,
var margins = ifrD.body.style.margin + ifrD.body.style.padding + ifrD.documentElement.style.margin + ifrD.documentElement.style.padding;
if(margins=="") { margins=0; if(overwrite_margin) { ifrD.body.style.margin="0px"; } }
(function(){
var interval = setInterval(function(){
if(ifrD.readyState == 'complete' ){
setTimeout( function(){
if(!cycling) { setTimeout( function(){ clearInterval(interval);}, 500); }
iframeElement.style.height = (parseInt(window.getComputedStyle( ifrD.documentElement).height) + parseInt(margins)+1) +"px";
}, 200 );
}
},200)
})();
//var funcname= arguments.callee.name;
//window.setTimeout( function(){ console.log(funcname); console.log(cycling); window[funcname](iframeElement, cycling); }, 500 );
}
getYtIdFromURL(URLL){let r=URLL.match(/^.*(?:(?:youtu\.be\/|v\/|vi\/|u\/\w\/|embed\/)|(?:(?:watch)?\?v(?:i)?=|\&v(?:i)?=))([^#\&\?]*).*/); return r[1];}
//state url change
//function processAjaxData(response, urlPath){
// document.getElementById("content").innerHTML = response.html;
// document.title = response.pageTitle;
// window.history.pushState({"html":response.html,"pageTitle":response.pageTitle},"", urlPath);
//}
//window.onpopstate = function(e){
// if(e.state){
// document.getElementById("content").innerHTML = e.state.html;
// document.title = e.state.pageTitle;
// }
//};
autoSizeTextareas(className)
{
let tx = document.querySelector(className);
for (let i = 0; i < tx.length; i++) {
tx[i].setAttribute('style', 'height:' + (tx[i].scrollHeight) + 'px;overflow-y:hidden;');
var oninput = function () {
this.style.height = 'auto';
this.style.height = (this.scrollHeight) + 'px';
};
tx[i].addEventListener("input", OnInput, false);
}
}
getAllMethods(obj, inherited_too)
{
var methods = [];
for (var m in obj) {
if (typeof obj[m] == "function" && ( inherited_too || obj.hasOwnProperty(m)) ) {
methods.push(m);
}
}
return methods;
}
hasMethod(obj, funcName, inherited_too)
{
if (obj==null) return null;
for (var m in obj) {
if (typeof obj[m] == "function" && ( inherited_too || obj.hasOwnProperty(m)) ) {
if (funcName==m) return true;
}
}
return false;
}
ConvertToHourMinSec(time){ //Output like "1:01" or "4:03:59" or "123:03:59"
var hrs = ~~(time / 3600); var mins = ~~((time % 3600) / 60); var secs = time % 60;
var hms=""; hms +=""+hrs+":"+(mins< 10 ? "0":""); hms +=""+mins+":"+(secs<10 ? "0":""); hms +=""+secs; return hms;
}
// =========== get device sizes ==========//
// http://ryanve.com/lab/dimensions/
getWindowSize(){
return {x:document.documentElement.clientWidth, y:document.documentElement.clientHeight} ;
}
removeItem(arr, value) {
var i = 0;
while (i < arr.length) {
if(arr[i] === value) {
arr.splice(i, 1);
} else {
++i;
}
}
return arr;
}
removeItemOnce(arr, value) {
var index = arr.indexOf(value);
if (index > -1) {
arr.splice(index, 1);
}
return arr;
}
toggleItemInArray(array, value, condition)
{
if (condition) array.push(value);
else this.removeItemOnce(array,value);
return array;
}
// avoid ccxt's bug for undefined : https://jsfiddle.net/Lpxsthw4/
mergeDeep(target, source) {
let output = Object.assign({}, target);
if (this.isObject(target) && this.isObject(source)) {
Object.keys(source).forEach(key => {
if (this.isObject(source[key])) {
if (!(key in target))
Object.assign(output, { [key]: source[key] });
else
output[key] = this.mergeDeep(target[key], source[key]);
} else {
const val= source[key] !== undefined ? source[key] : target[key];
Object.assign(output, { [key]: val });
}
});
}
return output;
}
getScrollbarWidth() {
var outer = document.createElement("div");
outer.style.visibility = "hidden";
outer.style.width = "100px";
outer.style.msOverflowStyle = "scrollbar";
document.body.appendChild(outer);
var widthNoScroll = outer.offsetWidth;
outer.style.overflow = "scroll";
var inner = document.createElement("div");
inner.style.width = "100%";
outer.appendChild(inner);
var widthWithScroll = inner.offsetWidth;
outer.parentNode.removeChild(outer);
return widthNoScroll - widthWithScroll;
}
// animation-css https://codepen.io/AKGD/pen/yvwQYZ
animationClick(element, animation, removeOrNot){
var $=jQuery;
element = $(element);
element.click(
function() {
element.addClass('animated ' + animation);
//wait for animation to finish before removing classes
if(removeOrNot){
window.setTimeout( function(){
element.removeClass('animated ' + animation);
}, 2000);
}
}
);
}
animationClickTarget(element, target, animation, removeOrNot){
var $=jQuery;
element = $(element);
element.click(
function() {
target.addClass('animated ' + animation);
//wait for animation to finish before removing classes
if(removeOrNot){
window.setTimeout( function(){
element.removeClass('animated ' + animation);
}, 2000);
}
}
);
}
datetime = new (class {
parentClass = null;
constructor(parentClass){
this.parentClass = parentClass;
}
mainClass() { return this.parentClass; }
// 0940 type time-ints
isBetweenHMS(target, start, end, equality) { } // datetime, int/datetime, int/datetime, bool
equalDays(d1,d2) {
return d1.getYear()==d2.getyear() && d1.getMonth()==d2.getMonth() && d1.getDate()==d2.getDate();
} // DateTime, DateTime
IsTodayStart(dt) { } // DateTime
GetWeekOfMonth(dt) { } // DateTime
GetWeekOfYear(dt) { } // DateTime
GetQuarter(dt) { } // DateTime
NumberToHMSstring(hhmmss) { } // int
// ZZ incorrect, need LOCAL/UTC: DatetimeToHMSstring(dt) { }, // DateTime
// HMSToTimeSpan(hhmmss) { }, // int
addNumberToHMS(hhmmss, added_or_subtracted) { } // int, int
DatetimeToStringUtc(dt, withMS = true, withTZ = true) {
var str = (new Date( dt || new Date() )).toISOString();
let finalStr = (withTZ ? str : str.replace("T", " ").replace("Z", ""));
return withMS ? finalStr : finalStr.split('.')[0]; //2022-07-09 15:25:00.276
}
DatetimeToStringLocal(dt, withMS = true, withT = false) {
const str = (dt || new Date()).toLocaleString('sv', {year:'numeric', month:'numeric', day:'numeric', hour:'numeric', minute:'numeric', second:'numeric', fractionalSecondDigits: 3}).replace(',', '.');
let finalStr = (withT ? str.replace(' ', 'T') : str);
return withMS ? finalStr : finalStr.split('.')[0]; //2022-07-09 19:25:00.276
}
// in some langs, the date object has distinctions, so the two below needs separated methods. However, the "date" object returned from them, are same, just the representation can be local or UTC depending user.
StringToDatetimeUtc(str, format=null, culture=null) { return new Date(str).getTime(); }
StringToDatetimeLocal(str, format=null, culture=null) { return new Date(str); }
StringToTimestampUtc(str, format=null, culture=null) { return new Date(str).getTime(); }
DatetimeUtc() {
var now = new Date();
var utc = new Date(now.getTime()); // + now.getTimezoneOffset() * 60000 is not needed !!!!!!
return utc;
} UtcDatetime() { return this.DatetimeUtc(); }
// UTC
TimestampUtc() {
return Math.floor(new Date().getTime());
} UtcTimestamp() { return this.TimestampUtc(); }
//i.e. input: "2021-03-08 11:59:00" | output : 1650000000000 (milliseconds)
// [DONT CHANGE THIS FUNC, I'VE REVISED]
DatetimeToTimestampUtc(dt) {
let offset = this.getOffsetFromUtc();
return ((((new Date( dt )).getTime()) / 1000) + 14400 - offset * 60* 60) * 1000;
} UtcTimestampFrom(dt) { return this.DatetimeToTimestampUtc(dt); }
TimestampUtcToDatetimeUtc(ts) {
var d = new Date(ts);
d.setHours(d.getHours());
return d;
} UtcTimestampToUtcDatetime(ts) { return this.TimestampUtcToDatetimeUtc(ts); }
// shorthands
MaxDate(d1, d2, d3=null) {}
MinDate(d1, d2, d3=null) {}
localDatetimeToUtcString(dt){ }
areSameDays(d1, d2){ }
// ##### added to JS #####
GetDayOfYear(dt) { return (dt || new Date()).getUTCDate(); }
StringToUtcString(str) {
return str.indexOf ('Z') > -1 || str.indexOf ('GMT') > -1 ? str : str + ' GMT+0000';
}
//i.e. input: 1650000000000 (milliseconds) | output : "2021-03-08 11:59:00"
UtcTimestampToLocalDatetime(ts) {
var d = new Date(ts);
d.setHours(d.getHours()); // + (offset==null) offset = this.getOffsetFromUtc();
return d;
// if (offset==null) offset = this.getOffsetFromUtc();
// var d = new Date(time);
// var utc = d.getTime() + (d.getTimezoneOffset() * 60000); //This converts to UTC 00:00
// var nd = new Date(utc + (3600000*offset));
// return nd; return nd.toLocaleString();
}
//i.e. input: 1650000000000 (milliseconds) | output : "2021-07-14T21:08:00.000Z"
// [DONT CHANGE THIS FUNC, I'VE REVISED]
UtcTimestampToUtcDatetimeString_OLD_CORRECT(epochtime, withTZ){
let d = new Date(epochtime);
let str =d.toISOString();
return (withTZ ? str : str.replace("T", " ").replace("Z", ""));
}
UtcTimestampToUtcDatetimeString(epochtime, withTZ){
let d = this.UtcTimestampToUtcDatetime(epochtime);
return this.DatetimeToStringUtc(d, true, withTZ);
}
getOffsetFromUtc(){
var dt = new Date();
return -dt.getTimezoneOffset()/60;
}
// https://stackoverflow.com/questions/8579861/how-to-convert-milliseconds-into-a-readable-date
stringToDate(str){ // i.. "2021-04-05 15:59:55 GMT+4"
return new Date( Date.parse(str) );
}
msGoneAfter(date){
return (new Date()-date);
}
getYMDHISFfromDate(dt, utc=true){
// todo ? is +1 needed for month ??
if (utc) {
return [dt.getUTCFullYear(), dt.getUTCMonth()+1, dt.getUTCDate(), dt.getUTCHours(), dt.getUTCMinutes(), dt.getUTCSeconds(), dt.getUTCMilliseconds()];
} else {
return [1900 + dt.getYear(), dt.getMonth()+1, dt.getDate(), dt.getHours(), dt.getMinutes(), dt.getSeconds(), dt.getMilliseconds()];
}
}
getYMDHISFfromDateWithZeros(dt, utc=true){
let y, M, d, h, m, s, f;
if (utc) {
y = dt.getUTCFullYear();
M = dt.getUTCMonth()+1;
d = dt.getUTCDate();
h = dt.getUTCHours();
m = dt.getUTCMinutes();
s = dt.getUTCSeconds();
f = dt.getUTCMilliseconds();