-
Notifications
You must be signed in to change notification settings - Fork 0
/
Bookmarked functions.js
1992 lines (1662 loc) · 68.1 KB
/
Bookmarked functions.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
javascript:(function bookmarkUsefulFunctions() {
/*********************************
******** Utilities ********
********************************/
const jsFunctionRegex = '^\(?\s*@?(?!if|constructor|switch|runInAction)(?:async )?(function )?(\w+)(?=(?:\s*=?\s*)\(.*\{[\s\n])';
window.sortObjectByKeys = function(obj) {
return Object.keys(obj).sort().reduce((sortedObj, key) => {
sortedObj[key] = obj[key];
return sortedObj;
}, {});
};
window.getCookie = function getCookie(cookieStr = document.cookie, key = '', {
decodeBase64 = true,
} = {}) {
const cookieObj = cookieStr.split('; ').reduce((obj, entry) => {
const keyVal = entry.split('=');
const key = decodeURIComponent(keyVal[0]);
let value = decodeURIComponent(keyVal.slice(1).join('='));
if (decodeBase64) {
try {
value = atob(value);
} catch (e) {
/* Not a Base64-encoded string */
}
}
obj[key] = value;
return obj;
}, {});
return key ? cookieObj[key] : cookieObj;
};
window.resetCookie = function() {
document.cookie = 'expires=Thu, 01 Jan 1970 00:00:01 GMT';
};
function getQueryParams(input = self.location.search + self.location.hash, { delimiter, } = {}) {
let fromString;
let fromObj;
let from2dMatrix;
if (typeof input === typeof '') {
fromString = input;
} else if (Array.isArray(input)) {
from2dMatrix = input;
} else if (typeof input === typeof {}) {
fromObj = input;
} else {
throw new TypeError(`Type "${typeof input}" is not supported. Please use a string or object.`);
}
if (fromObj) {
fromObj = { ...fromObj };
const hash = fromObj['#'] || '';
delete fromObj['#'];
const getEncodedKeyValStr = (key, val) => `${encodeURIComponent(key)}=${encodeURIComponent(val)}`;
const queryParamEntries = Object.entries(fromObj);
const queryString = queryParamEntries.length > 0
? `?${
queryParamEntries
.map(([ queryKey, queryValue ]) => {
if (Array.isArray(queryValue)) {
if (delimiter) {
return getEncodedKeyValStr(queryKey, queryValue.join(delimiter));
}
return queryValue
.map(val => getEncodedKeyValStr(queryKey, val))
.join('&');
}
if (queryValue == null) {
/* Convert null/undefined to empty string */
queryValue = '';
} else if (typeof queryValue === typeof {}) {
/* Stringify objects, arrays, etc. */
return getEncodedKeyValStr(queryKey, JSON.stringify(queryValue));
}
return getEncodedKeyValStr(queryKey, queryValue);
})
.join('&')
}`
: '';
return queryString + (hash ? `#${hash}` : '');
}
const queryParamsObj = {};
let urlSearchParamsEntries;
if (from2dMatrix) {
const stringifiedMatrixValues = from2dMatrix.map(([ key, value ]) => {
if (value && (typeof value === typeof {})) {
/* Arrays are objects so only one `typeof` check is needed */
value = JSON.stringify(value);
}
return [ key, value ];
});
urlSearchParamsEntries = [...new URLSearchParams(stringifiedMatrixValues).entries()];
} else {
const queryParamHashString = fromString.match(/([?#].*$)/i)?.[0] ?? '';
const [ urlSearchQuery, hash ] = queryParamHashString.split('#');
if (hash) {
queryParamsObj['#'] = hash;
}
urlSearchParamsEntries = [...new URLSearchParams(urlSearchQuery).entries()];
}
const attemptParseJson = (str) => {
try {
return JSON.parse(str);
} catch (e) {}
return str;
};
return urlSearchParamsEntries
.reduce((queryParams, nextQueryParam) => {
let [ key, value ] = nextQueryParam;
if (delimiter != null) {
value = value.split(delimiter);
if (value.length === 0) {
value = '';
} else if (value.length === 1) {
value = value[0];
}
}
if (Array.isArray(value)) {
value = value.map(val => attemptParseJson(val));
} else {
value = attemptParseJson(value);
}
if (key in queryParams) {
if (!Array.isArray(value)) {
value = [ value ]; /* cast to array for easier boolean logic below */
}
/* Remove duplicate entries using a Set, which maintains insertion order in JS */
let newValuesSet;
if (Array.isArray(queryParams[key])) {
newValuesSet = new Set([
...queryParams[key],
...value,
]);
} else {
newValuesSet = new Set([
queryParams[key],
...value,
]);
}
queryParams[key] = [ ...newValuesSet ]; /* Cast back to an array */
} else {
queryParams[key] = value;
}
return queryParams;
}, queryParamsObj);
};
window.getQueryParams = getQueryParams;
/**
* Extracts the different segments from a URL segments and adds automatic parsing of query parameters/hash
* into an object. Also normalizes resulting strings to never contain a trailing slash.
*
* @param url - URL to parse for query parameters
* @returns URL segments.
*/
function getUrlSegments(url = '') {
let fullUrl = url;
let protocol = '';
let domain = '';
let port = '';
let origin = '';
let pathname = '';
let queryString = '';
let queryParamHashString = '';
let hash = '';
try {
({
href: fullUrl,
origin,
protocol,
hostname: domain,
port,
pathname,
search: queryString,
hash, /* empty string or '#...' */
} = new URL(url));
} catch (e) {
/*
* Either `URL` isn't defined or some other error, so try to parse it manually.
*
* All regex strings use `*` to mark them as optional when capturing so that
* they're always the same location in the resulting array, regardless of whether
* or not they exist.
*
* URL segment markers must each ignore all special characters used by
* those after it to avoid capturing the next segment's content.
*/
const protocolRegex = '([^:/?#]*://)?'; /* include `://` for `origin` creation below */
const domainRegex = '([^:/?#]*)'; /* capture everything after the protocol but before the port, pathname, query-params, or hash */
const portRegex = '(?::)?(\\d*)'; /* colon followed by digits; non-capture must be outside capture group so it isn't included in output */
const pathnameRegex = '([^?#]*)'; /* everything after the origin (starts with `/`) but before query-params or hash */
const queryParamRegex = '([^#]*)'; /* everything before the hash (starts with `?`) */
const hashRegex = '(.*)'; /* anything leftover after the above capture groups have done their job (starts with `#`) */
const urlPiecesRegex = new RegExp(`^${protocolRegex}${domainRegex}${portRegex}${pathnameRegex}${queryParamRegex}${hashRegex}$`);
[
fullUrl,
protocol,
domain,
port,
pathname,
queryString,
hash,
] = urlPiecesRegex.exec(url);
origin = protocol + domain + (port ? `:${port}` : '');
}
queryParamHashString = queryString + hash;
/* protocol can be `undefined` due to having to nest the entire thing in `()?` */
protocol = (protocol || '').replace(/:\/?\/?/, '');
/* normalize strings: remove trailing slashes and leading ? or # */
fullUrl = fullUrl.replace(/\/+(?=\?|#|$)/, ''); /* fullUrl could have `/` followed by query params, hash, or end of string */
origin = origin.replace(/\/+$/, '');
pathname = pathname.replace(/\/+$/, '');
queryString = queryString.substring(1);
hash = hash.substring(1);
const queryParamMap = getQueryParams(queryParamHashString);
return {
fullUrl,
protocol,
domain,
port,
origin,
pathname,
queryParamHashString,
queryParamMap,
queryString,
hash,
};
};
window.getUrlSegments = getUrlSegments;
/**
* Hashes a string using the specified algorithm.
*
* Defaults to SHA-256. Available algorithms exist in the `hash.ALGOS` object.
*
* @param {string} str - String to hash.
* @param {typeof hash.ALGOS[keyof hash.ALGOS]} [algo] - Algorithm to use.
* @returns The hashed string.
*
* @see [Crypto.subtle hashing API]{@link https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto/digest#converting_a_digest_to_a_hex_string}
* @see [Boilerplate crypto utils]{@link https://github.com/D-Pow/react-app-boilerplate/blob/master/src/utils/Crypto.ts}
*/
window.hash = async function hash(str, {
algo = hash.ALGOS.Sha256,
} = {}) {
const validAlgorithms = new Set(Object.values(hash.ALGOS));
if (!validAlgorithms.has(algo)) {
throw new TypeError(`Error: Hash algorithm "${algo}" not supported. Valid values are: [ ${[ ...validAlgorithms ].join(', ')} ].`);
}
/* Encode to (UTF-8) Uint8Array */
const utf8IntArray = new TextEncoder().encode(str);
/* Hash the string */
const hashBuffer = await self.crypto.subtle.digest(algo, utf8IntArray);
/* Get hex string from buffer/byte array */
const hashAsciiHex = byteArrayToHexString(new Uint8Array(hashBuffer));
return hashAsciiHex;
};
hash.ALGOS = {
Sha1: 'SHA-1',
Sha256: 'SHA-256',
Sha384: 'SHA-384',
Sha512: 'SHA-512',
};;
/** @see [Boilerplate text utils]{@link https://github.com/D-Pow/react-app-boilerplate/blob/master/src/utils/Text.js} */
window.byteArrayToHexString = function byteArrayToHexString(uint8Array, {
hexPrefix = '',
hexDelimiter = '',
asArray = false,
} = {}) {
const hexStrings = [ ...uint8Array ].map(byte => byte.toString(16).padStart(2, '0'));
const hexStringsWithPrefixes = hexStrings.map(hexString => `${hexPrefix}${hexString}`);
if (asArray) {
return hexStringsWithPrefixes;
}
return hexStringsWithPrefixes.join(hexDelimiter);
};
/** @see [Boilerplate Date utils]{@link https://github.com/D-Pow/react-app-boilerplate/blob/master/src/utils/Dates.ts} */
window.diffDateTime = function diffDateTime(
earlier = new Date(),
later = new Date(),
) {
let earlierDate = new Date(earlier);
let laterDate = new Date(later);
if (laterDate.valueOf() < earlierDate.valueOf()) {
const earlierDateOrig = earlierDate;
earlierDate = laterDate;
laterDate = earlierDateOrig;
}
const diffDateObj = {
years: laterDate.getFullYear() - earlierDate.getFullYear(),
months: laterDate.getMonth() - earlierDate.getMonth(),
dates: laterDate.getDate() - earlierDate.getDate(),
hours: laterDate.getHours() - earlierDate.getHours(),
minutes: laterDate.getMinutes() - earlierDate.getMinutes(),
seconds: laterDate.getSeconds() - earlierDate.getSeconds(),
milliseconds: laterDate.getMilliseconds() - earlierDate.getMilliseconds(),
};
Object.entries(diffDateObj).reverse().forEach(([ key, val ], i, entries) => {
const nextEntry = entries[i + 1];
if (!nextEntry) {
return;
}
const [ nextKey, nextVal ] = nextEntry;
const timeConfig = diffDateTime.ordersOfMagnitude[key];
if (val < 0) {
diffDateObj[key] = numberToBaseX(diffDateObj[key], timeConfig.maxValue, { signed: false });
diffDateObj[nextKey] = nextVal - 1;
}
});
diffDateObj.days = diffDateObj.dates;
delete diffDateObj.dates;
return diffDateObj;
};
diffDateTime.ordersOfMagnitude = {
milliseconds: {
maxValue: 1,
},
seconds: {
maxValue: 60,
},
minutes: {
maxValue: 60,
},
hours: {
maxValue: 24,
},
days: {
maxValue: 7,
},
weeks: {
maxValue: 4,
},
dates: {
maxValue: 31,
},
months: {
maxValue: 12,
},
years: {
maxValue: 1,
},
};
/**
* Mods two numbers with a custom radix; i.e. Makes `num1 % num2` have a max of a
* certain number, regardless of positive or negative mod value.
* Helpful for stuff like diffing minutes relative to the max minute possible, 60.
*
* e.g. If the date diff of the first date resulted in a negative minute value (-52)
* and the later date had a positive value (30) and you want to diff the minutes
* relative to a "radix" of 60, then:
* min1 = -52
* min2 = 30
* -52 % 30 =
* -22 (signed)
* 8 (unsigned)
*/
window.numberToBaseX = function numberToBaseX(num, base, {
signed = true,
} = {}) {
const signedModBase = num % base;
if (!signed) {
/* Converts e.g. -52 % 30 => 8 instead of -22 */
return (signedModBase + base) % base;
}
return signedModBase;
};
window.getAlphabet = function getAlphabet({
lowercase = true,
uppercase = true,
} = {}) {
const getUpperOrLowerCaseAlphabetFromA = startCharCode => Array.from({ length: 26 })
.map((nul, index) => index + startCharCode)
.map(charCode => String.fromCharCode(charCode));
const alphabetLowercase = getUpperOrLowerCaseAlphabetFromA('a'.charCodeAt(0));
const alphabetUppercase = getUpperOrLowerCaseAlphabetFromA('A'.charCodeAt(0));
if (lowercase && uppercase) {
return [ ...alphabetLowercase, ...alphabetUppercase ];
}
if (lowercase) {
return alphabetLowercase;
}
if (uppercase) {
return alphabetUppercase;
}
};
window.htmlEscape = str => {
return str
.replace(/&/g, '&')
.replace(/</g, '<')
.replace(/>/g, '>')
.replace(/"/g, '"')
.replace(/'/g, ''')
.replace(/\//g, '/');
};
window.htmlUnescape = str => {
return str
.replace(/&/g, '&')
.replace(/</g, '<')
.replace(/>/g, '>')
.replace(/"/g, '"')
.replace(/'/g, "'")
.replace(///g, '/');
};
window.getElementAttributes = elem => [ ...(elem.attributes) ] /* `attributes` is a `NamedNodeMap`: https://developer.mozilla.org/en-US/docs/Web/API/NamedNodeMap */
.reduce((attrsObj, { name, value }) => ( /* Grab desired keys from the `Attr` object: https://developer.mozilla.org/en-US/docs/Web/API/Attr */
(attrsObj[name] = value)
&& attrsObj /* Use short-circuiting to ensure we always return the `attrsObj` without having to convert this to a full blown function like `(args) => { myLogic; return attrsObj; }` */
|| attrsObj
), {});
/**
* Makes a class iterable, adding an implementation of `Class.prototype[Symbol.iterator]`.
*
* @param {Object} cls - Class to make iterable.
* @param {string} nextLikeFuncName - The name of the function generating values, to be called like an iterator's `next()` function.
* @param {Object} [options]
* @param {boolean} [options.force] - Force overwriting of any preexisting iterator implementations.
* @param {Object} [options.trackItemsOnNextCall] - Keep track of all values returned from the next-like function;
* Useful for when items are deleted after being read (e.g. NodeIterator, TreeWalker)
* or when the next-like function will generate new items over time and you want the
* iterator to track them.
* @returns {void}
*
* @see [Implementation inspiration]{@link https://github.com/whatwg/dom/issues/704}
* @see [Iterable/Iterator protocols]{@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols}
*/
function makeClassIterable(cls, nextLikeFuncName, {
trackItemsOnNextCall = false,
force = false,
} = {}) {
const clsName = cls.name || cls.prototype.constructor.name;
const nextLikeFunc = cls.prototype[nextLikeFuncName];
const isIterable = cls.prototype[Symbol.iterator] instanceof Function;
if (!(nextLikeFunc && nextLikeFunc instanceof Function)) {
throw new TypeError(`${clsName}.prototype.${nextLikeFuncName} is not a function`);
}
if (isIterable) {
console.warn(`${clsName}.prototype[Symbol.iterator] already exists`);
if (!force) {
return;
}
console.log(`Overwriting ${clsName}.prototype[Symbol.iterator]...`);
}
/* Use `function` instead of arrow function so `this` works on the class instance */
function* iteratorFunc() {
let nextValue;
while ((nextValue = this[nextLikeFuncName]()) != null) {
yield nextValue;
}
}
function makeIterator(trackItems = false) {
if (trackItems) {
const values = [];
let iterator;
let iteratorExhausted = false;
/* TODO Extract this out to its own function and make it possible to reset iterators */
return function* () {
/*
* Neither `makeIterator` nor `iteratorFunc` are bound to the class because `makeIterator`
* is not a generator/doesn't return an iterator and is called in the context of the parent
* who called this function (e.g. `window` if in dev tools, a different class, or some script).
*
* Thus, bind `this` to `iteratorFunc` within this anonymous function b/c it is called on
* the class instance itself (i.e. when `clsInstance[Symbol.iterator]()` is called), giving
* it the correct value of `this`.
*
* Note: we don't need to `bind(this)` if returning the `iteratorFunc` itself b/c it will
* be called on the class instance, not from the parent context nor within another function.
*/
const bindIteratorFunc = () => iterator = iteratorFunc.bind(this)();
if (!iterator) {
bindIteratorFunc();
}
if (iteratorExhausted) {
/*
* Delegate this (returned) generator's iterator logic to Array.prototype[Symbol.iterator]
* since all items have been deleted.
* Then, reset the `iterator` to a new instance from `iteratorFunc` to capture any values
* that might be added after the first iteration (which also means don't return from the
* function here, either).
*/
yield* values;
bindIteratorFunc();
}
let value;
/*
* Set the `next()` output to `value` and `done` variables, then use JS' internal/natural return
* logic of statement executions to read the `next()` return object's `done` field (which was copied)
* into the local variable)
*/
while (!({ value } = iterator.next()).done) {
values.push(value);
yield value;
}
iteratorExhausted = true;
};
}
return iteratorFunc;
}
cls.prototype[Symbol.iterator] = makeIterator(trackItemsOnNextCall);
};
window.makeClassIterable = makeClassIterable;
/**
* Finds all Nodes/Elements through custom logic that can't be captured by CSS query selectors.
*
* Useful cases include:
* - innerText
* - All attribute values (i.e. CSS selector akin to `[.* *= 'my-search-text']`)
* - Custom "is a parent/child of" logic (i.e. skipping over any elements whose parent is <h1> for performance improvements)
*
* @param {function} nodeFilterFunc - Filter function; `(Node) => boolean | NodeFilter.FILTER_[X]`.
* @param {Object} [options]
* @param {boolean} [options.useCustomNodeIteratorReturn] - If `nodeFilterFunc` returns a `NodeFilter` property instead of a boolean (see `useNodeIterator` example).
* @param {Object} [options.useNodeIterator] - If a `NodeIterator` should be used instead of `document.querySelectorAll('*')`;
* Typically only useful if your filter function wants to return a custom `NodeIterator`
* value, which is generally only used over `querySelectorAll()` to improve performance
* by e.g. dropping entire DOM sub-trees so they aren't searched, i.e.
* `return node.tagName.match(/div/i) ? NodeFilter.FILTER_REJECT : node.innerText === 'hi' ? NodeFilter.FILTER_ACCEPT : NodeFilter.FILTER_SKIP;`.
* @return {Node[]} - Array of matching [DOM Nodes]{@link https://developer.mozilla.org/en-US/docs/Web/API/Node}.
*
* @see [When to use NodeIterator instead of querySelectorAll]{@link https://stackoverflow.com/questions/7941288/when-to-use-nodeiterator/58221592}
* @see [NodeIterator]{@link https://developer.mozilla.org/en-US/docs/Web/API/NodeIterator}
* @see [NodeFilter]{@link https://developer.mozilla.org/en-US/docs/Web/API/NodeFilter}
* @see [CSS Selectors]{@link https://www.w3schools.com/cssref/css_selectors.asp}
* @see [innerText vs textContent]{@link https://developer.mozilla.org/en-US/docs/Web/API/Node/textContent#differences_from_innertext}
* @see [Xpath vs TreeWalker vs manual element iteratation]{@link https://stackoverflow.com/questions/3813294/how-to-get-element-by-innertext}
* @see [Secret CSS Selector finds by attribute, but has no documentation anywhere]{@link https://stackoverflow.com/a/42479114}
*/
function findElementsByAnything(nodeFilterFunc, {
useNodeIterator = false,
useCustomNodeIteratorReturn = false,
} = {}) {
if (useNodeIterator || useCustomNodeIteratorReturn) {
const nodeIterator = document.createNodeIterator(
document.body,
NodeFilter.SHOW_ELEMENT,
{
acceptNode(node) {
if (useCustomNodeIteratorReturn) {
return nodeFilterFunc(node);
}
return nodeFilterFunc(node) ? NodeFilter.FILTER_ACCEPT : NodeFilter.FILTER_REJECT;
}
}
);
const nodeMatches = [];
let currentNode;
while (currentNode = nodeIterator.nextNode()) {
nodeMatches.push(currentNode);
}
return nodeMatches;
}
return [ ...document.body.querySelectorAll('*') ].filter(nodeFilterFunc);
};
window.findElementsByAnything = findElementsByAnything;
window.setDocumentReferer = function(url = null, useOrigin = false) {
if (!url) {
/*
* Create <meta name="referrer" content="never" />
* This header removes all referrer headers completely
*/
const meta = document.createElement('meta');
meta.name = 'referrer';
meta.content = 'never';
document.head.appendChild(meta);
return;
}
let referrerUrl = url;
if (useOrigin) {
const originRegex = /(?<=https:\/\/)[^/]+/;
referrerUrl = url.match(originRegex)[0];
}
delete document.referrer;
document.__defineGetter__('referrer', () => referrerUrl);
};
/**
* fetch() using CORS proxy
*
* Fetch API: https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch
* Fetch API + CORS: https://developers.google.com/web/ilt/pwa/working-with-the-fetch-api
* Using CORS proxy: https://stackoverflow.com/a/43268098/5771107
* CORS proxy: https://cors-anywhere.herokuapp.com/ + URL (e.g. https://www.rapidvideo.com/e/FUM5608RR8)
*
* Attempt at using headers for getting video from rapidvideo.com
* headers: {
* 'X-Requested-With': 'XMLHttpRequest',
* // rest aren't needed
* 'Accept-Encoding': 'gzip, deflate, br',
* 'Accept-Language': 'en-US,en;q=0.9',
* 'Cache-Control': 'no-cache',
* 'Connection': 'keep-alive',
* // 'Cookie': 'key1=val1; key2=val2',
* 'DNT': '1',
* 'Host': 'www.rapidvideo.com',
* 'Pragma': 'no-cache',
* 'Referer': 'https://kissanime.ru/Anime/Boku-no-Hero-Academia-3rd-Season/Episode-059?id=149673&s=rapidvideo',
* 'Upgrade-Insecure-Requests': '1',
* 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.157 Safari/537.36'
* }
*
* @param {string} url - URL for network request.
* @param {RequestInit} options - Options for `fetch()`.
* @param {boolean} [useCorsAnywhereApp=false] - Use https://cors-anywhere.herokuapp.com/ (restricted and close to deprecation) instead of Anime Atsume.
*/
window.fetchCors = function(url, options, useCorsAnywhereApp = false) {
if (useCorsAnywhereApp) {
const corsAnywhereRequiredHeaders = {
'X-Requested-With': 'XMLHttpRequest'
};
const fetchOptions = options
? {
...options,
headers: {
...options?.headers,
...corsAnywhereRequiredHeaders
}
} : {
headers: corsAnywhereRequiredHeaders
};
return fetch(
'https://cors-anywhere.herokuapp.com/' + url,
{...fetchOptions}
);
}
const animeAtsumeCorsUrl = 'https://anime-atsume.herokuapp.com/corsProxy?url=';
const defaultAnimeAtsumeCorsOptions = {
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
},
};
const requestOptions = {
...options,
headers: {
...defaultAnimeAtsumeCorsOptions.headers,
...options?.headers,
},
};
const encodedUrl = animeAtsumeCorsUrl + encodeURIComponent(url);
return fetch(encodedUrl, requestOptions);
};
window.compareEscapingFunctions = function() {
/* TL;DR Don't use escape(), use encode() or custom/third-party
* See: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/encodeURIComponent#description
*/
const encodedCharsByFunc = Array.from({ length: 256 })
.reduce((charsThatWillBeEncoded, nil, i) => {
const asciiChar = String.fromCharCode(i);
const charEncodes = {
char: asciiChar
};
if (asciiChar !== encodeURI(asciiChar)) {
charEncodes.encodeURI = encodeURI(asciiChar);
}
if (asciiChar !== encodeURIComponent(asciiChar)) {
charEncodes.encodeURIComponent = encodeURIComponent(asciiChar);
}
if (asciiChar !== escape(asciiChar)) {
charEncodes.escape = escape(asciiChar);
}
if (Object.keys(charEncodes).length > 1) {
charsThatWillBeEncoded.push(charEncodes);
}
return charsThatWillBeEncoded;
}, []);
console.table(encodedCharsByFunc);
return encodedCharsByFunc;
};
/**********************************
******** Life utils *******
*********************************/
window.celsiusFahrenheit = function ({
c,
f,
} = {}) {
if (!c && !f) {
throw new TypeError('Either `c` or `f` must be specified');
}
if (c) {
return (c * 9/5) + 32;
}
if (f) {
return (f - 32) * 5/9;
}
return NaN;
};
window.kilogramsPounds = function ({
kg,
lbs,
} = {}) {
if (!kg && !lbs) {
throw new TypeError('Either `kg` or `lbs` must be specified');
}
const kgToLbsRatio = 2.20462;
if (lbs) {
return lbs * (1 / kgToLbsRatio); /* ~ 0.453592 */
}
if (kg) {
return kg * kgToLbsRatio;
}
return NaN;
};
window.ouncesPounds = function ({
oz,
lbs,
} = {}) {
if (!oz && !lbs) {
throw new TypeError('Either `oz` or `lbs` must be specified');
}
const ozToLbsRatio = 16;
if (oz) {
return oz * (1 / ozToLbsRatio);
}
if (lbs) {
return lbs * ozToLbsRatio;
}
return NaN;
};
window.gramsOunces = function ({
g,
oz,
} = {}) {
if (!g && !oz) {
throw new TypeError('Either `g` or `oz` must be specified');
}
const gToOzRatio = 28.3495;
if (g) {
return g * (1 / gToOzRatio);
}
if (oz) {
return oz * gToOzRatio;
}
return NaN;
};
window.ouncesMilliliters = function ({
oz,
ml,
} = {}) {
if (!oz && !ml) {
throw new TypeError('Either `oz` or `ml` must be specified');
}
const mlToOzRatio = 0.033814;
if (oz) {
return oz * (1 / mlToOzRatio);
}
if (ml) {
return ml * mlToOzRatio;
}
return NaN;
};
window.inchesMillimeters = function ({
inches,
mm,
} = {}) {
if (!inches && !mm) {
throw new TypeError('Either `inches` or `mm` must be specified');
}
const inchesToMmRatio = 25.4;
if (mm) {
return mm / inchesToMmRatio; /* 1 inch = 25.4 mm */
}
if (inches) {
return inches * inchesToMmRatio; /* 1 mm = 0.0393701 in */
}
return NaN;
};
/**
* @typedef BacConfig
* @property {number} hoursElapsed - Number of hours elapsed while drinking.
* @property {boolean} isMale - If the person is a male.
* @property {boolean} isDrinkVolumeOunces - If using oz for drink volume instead of mL.
* @property {boolean} isBodyWeightPounds - If using lbs for body weight instead of kg.
*/
/**
* @typedef BacDrink
* @extends BacConfig
* @property {number} drinkVolume - Volume of the drink.
* @property {number} drinkPercentage - Alcohol percentage of the drink
* @property {number} hoursElapsed - Number of hours elapsed while drinking.
* @property {number} bodyWeight - Person's body weight (defaults to lbs, modify {@code BacConfig.isBodyWeightPounds} options object for kg).
*/
/**
* Estimates the blood alcohol concentration (BAC) after drinking over a period of time.
*
* Not 100% accurate due to differences in bodies' metabolism and other factors, but gives
* a reasonable rough estimate.
*
* @param {(number | ({ drinks: Array<BacDrink>; }))} drinkVolume - Volume of the drink/drinks, or options config object.
* @param {number} drinkPercentage - Alcohol percentage of the drink(s).
* @param {number} bodyWeight - Person's body weight (defaults to lbs, modify {@code BacConfig.isBodyWeightPounds} options object for kg).
* @param {BacConfig} [options]
* @returns {number} - Estimated BAC.
*
* @see [Wikipedia article supplying the formula]{@link https://en.wikipedia.org/wiki/Blood_alcohol_content#By_intake}
*/
window.bac = function bac(drinkVolume, drinkPercentage, bodyWeight, {
hoursElapsed = 1,
isMale = true,
isDrinkVolumeOunces = true,
isBodyWeightPounds = true,
} = {}) {
if (typeof drinkVolume === typeof {}) {
const fullConfig = drinkVolume;
/* Options with fallback to default values */
drinkPercentage = fullConfig.drinkPercentage ?? drinkPercentage;
bodyWeight = fullConfig.bodyWeight ?? bodyWeight;
isMale = fullConfig.isMale ?? isMale;
isDrinkVolumeOunces = fullConfig.isDrinkVolumeOunces ?? isDrinkVolumeOunces;
isBodyWeightPounds = fullConfig.isBodyWeightPounds ?? isBodyWeightPounds;
return fullConfig.drinks.reduce((totalBac, { drinkVolume, drinkPercentage: customDrinkPercentage, hoursElapsed }) => (
totalBac + bac(drinkVolume, customDrinkPercentage || drinkPercentage, bodyWeight, {
hoursElapsed,
isMale,
isDrinkVolumeOunces,
isBodyWeightPounds,
})
), 0);
}
if (!drinkVolume) {
throw new Error('`drinkVolume` must be specified.');
}
if (!drinkPercentage) {
throw new Error('`drinkPercentage` must be specified.');
}
if (!bodyWeight) {
throw new Error('`bodyWeight` must be specified.');
}
if (isDrinkVolumeOunces) {
drinkVolume *= 29.5735; /* 1 oz == 29.5735 ml */
}
if (isBodyWeightPounds) {
bodyWeight *= 0.453592; /* 1 lbs == 0.453592 kg */
}
const alcoholMassUnit = 1000; /* 1000 g == 1 kg; 16 oz == 1 lb, but no need to worry about that since it's converted to grams above */
const alcoholMetabolismRate = isMale ? 0.015 : 0.017; /* Males process alcohol slower than females on average */
const bodyWaterToBodyWeightRatio = isMale ? 0.68 : 0.55; /* Males have less body fat than females, thus have more water */
/* See: https://www.engineeringtoolbox.com/ethanol-water-mixture-density-d_2162.html */
const alcoholWaterDensityAt20Celsius = 0.935;
const alcoholWaterDensityAt25Celsius = 0.931;
const alcoholWaterDensity = (alcoholWaterDensityAt20Celsius + alcoholWaterDensityAt25Celsius) / 2;
const bloodDensity = 1.055; /* g/mL */