@antti5/ship-tool-common 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/Util.js ADDED
@@ -0,0 +1,789 @@
1
+ class Util {
2
+
3
+ /* Sleep the given number of milliseconds.
4
+
5
+ The executor function given to the Promise constructor simply sets a timeout to call
6
+ the resolve function. The Promise is never rejected. */
7
+
8
+ static async sleep(ms) {
9
+ await new Promise(res => setTimeout(res, ms));
10
+ }
11
+
12
+
13
+ /* Wrapper for Window.fetch(). On success the response body is returned as a JavaScript
14
+ object, or as Javascript string if the response headers don't indicate the body to be JSON.
15
+
16
+ If the environment variable VITE_FETCH_CACHE_MS is set, then fetch responses for each URL
17
+ are cached for the given number of milliseconds.
18
+
19
+ If the option "urlSearchParams" is received, it is expected to be an object containing
20
+ name-value pairs, and is turned into a URLSearchParams object.
21
+
22
+ If Window.fetch() throws an exception, e.g. on badly formatted request or network error,
23
+ then this exception is NOT caught.
24
+
25
+ If Window.fetch() returns a response with other than 2** status code, then an exception
26
+ is thrown. The error message contains the HTTP status text and code, and the "cause" property
27
+ contains the Window.fetch() response object. */
28
+
29
+ static #fetchResponse = {};
30
+
31
+ static async fetch (url, {
32
+ urlSearchParams,
33
+ method = 'GET',
34
+ body,
35
+ headers = {},
36
+ timeout,
37
+ debug
38
+ } = {}) {
39
+
40
+ if (urlSearchParams)
41
+ url += '?' + new URLSearchParams(urlSearchParams);
42
+
43
+ const cacheMs = Number(
44
+ typeof process !== 'undefined' ?
45
+ process.env?.VITE_FETCH_CACHE_MS : // Vitest
46
+ import.meta?.env?.VITE_FETCH_CACHE_MS // Development and production
47
+ );
48
+
49
+ if (cacheMs && Util.#fetchResponse[url]?.timestamp + cacheMs > Date.now()) {
50
+ console.debug('Returning cached response for URL', url);
51
+ return Util.#fetchResponse[url].body;
52
+ }
53
+
54
+ if (debug)
55
+ console.debug('fetch()', method, url);
56
+
57
+ const requestHeaders = { ...headers };
58
+ if (body)
59
+ requestHeaders['Content-Type'] = 'application/json';
60
+ const response = await fetch(url, {
61
+ method,
62
+ body: body ?
63
+ JSON.stringify(body) :
64
+ undefined,
65
+ headers: requestHeaders,
66
+ signal: timeout ?
67
+ AbortSignal.timeout(timeout) :
68
+ undefined
69
+ });
70
+
71
+ if (debug)
72
+ console.debug('fetch() response:', response);
73
+
74
+ if (!response.ok)
75
+ throw new Error(`${response.statusText} (${response.status})`, { cause: response });
76
+
77
+ const responseBody =
78
+ response.headers.get('Content-Type')?.includes('application/json') ?
79
+ await response.json() :
80
+ await response.text(); // If response isn't JSON, return a String instead -- TODO: This may be very poor design
81
+
82
+ if (debug)
83
+ console.debug('fetch() response body:', responseBody);
84
+
85
+ if (cacheMs) {
86
+ console.debug('Caching response for URL', url);
87
+ Util.#fetchResponse[url] = {
88
+ timestamp: Date.now(),
89
+ body: responseBody
90
+ };
91
+ }
92
+
93
+ return responseBody;
94
+ }
95
+
96
+ static #getEnvironment() {
97
+ return typeof process !== 'undefined' ?
98
+ process.env.NODE_ENV.trim() :
99
+ import.meta.env.MODE.trim();
100
+ }
101
+
102
+ static #isProduction() {
103
+ return window.location.host.endsWith('shiptool.st');
104
+ }
105
+
106
+ static envDevelopment() {
107
+ return Util.#getEnvironment() === 'development';
108
+ }
109
+
110
+ static envTest() {
111
+ return Util.#getEnvironment() === 'test';
112
+ }
113
+
114
+ static envDeployed() {
115
+ return Util.#getEnvironment() === 'production';
116
+ }
117
+
118
+ static envDeployedProduction() {
119
+ return Util.envDeployed() && Util.#isProduction();
120
+ }
121
+
122
+ static envDeployedTest() {
123
+ return Util.envDeployed() && !Util.#isProduction();
124
+ }
125
+
126
+ static envExperimental() {
127
+ return !Util.envDeployedProduction() && !window.ST_NO_EXPERIMENTAL;
128
+ }
129
+
130
+
131
+ /* Generated random numbers and index for the next number. */
132
+
133
+ static #randoms = [];
134
+ static #randomsIndex = 0;
135
+
136
+ /* Get a random number, either from the #randoms array or create and store a new one. */
137
+
138
+ static random() {
139
+ if (Util.#randomsIndex === Util.#randoms.length)
140
+ Util.#randoms.push(Math.random());
141
+ return Util.#randoms[Util.#randomsIndex++];
142
+ }
143
+
144
+ /* Switch back to the start of randoms array to return the same random numbers again. */
145
+
146
+ static randomReset() {
147
+ Util.#randomsIndex = 0;
148
+ }
149
+
150
+
151
+ /* Return an UID with the following properties:
152
+
153
+ 1) Length is fixed at 10 characters.
154
+ 2) Used characters are 0-9, a-z and A-Z.
155
+ 3) Characters at both ends of the UID change more often.
156
+ 4) Uniqueness in the same process is guaranteed for 25 years.
157
+ 5) If UIDs are created in two different processes within a one-second time
158
+ window, the probability of a collision is less than one in billion. */
159
+
160
+ static #uidOldTimestamp = null;
161
+ static #uidCounter = null;
162
+
163
+ static uid() {
164
+
165
+ const DIGITS = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
166
+ const BASE = DIGITS.length;
167
+ const TIMESTAMP_DIGITS = 7;
168
+ const TIMESTAMP_WRAPAROUND_YEARS = 25;
169
+ const COUNTER_DIGITS = 3;
170
+
171
+ /* Return a positive integer in a different base. */
172
+
173
+ const ntoaBase = n => {
174
+ let result = '';
175
+ while (n >= BASE) {
176
+ result = DIGITS[n % BASE] + result;
177
+ n = Math.floor(n / BASE);
178
+ };
179
+ return DIGITS[n % BASE] + result;
180
+ };
181
+
182
+ /* Create a timestamp value that as a 7-digit base-62 number wraps around every 25 years.
183
+ Timestamp value changes every 0.224 milliseconds. */
184
+
185
+ const timestampMax = BASE ** TIMESTAMP_DIGITS;
186
+ const msPerTimestamp =
187
+ 1 / (timestampMax / TIMESTAMP_WRAPAROUND_YEARS / 365 / 24 / 60 / 60 / 1000);
188
+ const timestamp = Math.abs(Math.floor(Date.now() / msPerTimestamp) % timestampMax);
189
+
190
+ /* Create a counter value represented as a 3-digit base-62 number. If the timestamp is
191
+ different from previous call the counter value is reset to a random value to avoid using
192
+ the same counter value in different processes.
193
+
194
+ If the timestamp has not changed, however, the counter is incremented by one to guarantee
195
+ 62 ** 3 = 238328 different UIDs with the same timestamp value. */
196
+
197
+ const counterMax = BASE ** COUNTER_DIGITS;
198
+ if (timestamp !== Util.#uidOldTimestamp)
199
+ Util.#uidCounter = Math.floor(Math.random() * counterMax);
200
+ else
201
+ Util.#uidCounter = (Util.#uidCounter + 1) % counterMax;
202
+ Util.#uidOldTimestamp = timestamp;
203
+
204
+ /* Counter value is first in the UID because it's more random, thus providing more random
205
+ characters at the start of the UID. Counter value is reversed so that the first character
206
+ changes when several UIDs are created with the same timestamp value. */
207
+
208
+ let uid = '';
209
+ ntoaBase(Util.#uidCounter).padStart(COUNTER_DIGITS, '0').split('').reverse().forEach(c => uid += c);
210
+ uid += ntoaBase(timestamp).padStart(TIMESTAMP_DIGITS, '0');
211
+ return uid;
212
+ }
213
+
214
+
215
+ static perfObject(key) {
216
+ window.ST_PERF ??= {};
217
+ window.ST_PERF[key] ??= [];
218
+ return window.ST_PERF[key];
219
+ }
220
+
221
+ static perfStart() {
222
+ return performance.now();
223
+ }
224
+
225
+ static perfEndMany(count, startTime, key, { log } = {}) {
226
+ const ms = performance.now() - startTime;
227
+ const o = Util.perfObject(key);
228
+
229
+ for (let i = 0; i < count; i++)
230
+ o.push(ms / count);
231
+
232
+ if (log) {
233
+ console.debug('Performance:', `${count}x`, key, Util.round(ms / count, 2), 'ms');
234
+ if (count > 1)
235
+ console.debug('Performance: Total:', Util.round(ms, 2), 'ms');
236
+ }
237
+ }
238
+
239
+ static perfEnd(...args) {
240
+ return Util.perfEndMany(1, ...args);
241
+ }
242
+
243
+ static perfReport() {
244
+ const result = {};
245
+ for (const [key, values] of Object.entries(window.ST_PERF ?? {}))
246
+ result[key] = {
247
+ count: values.length,
248
+ total: values.reduce((sum, ms) => sum + ms).toFixed(2) + ' ms',
249
+ avg: (values.reduce((sum, ms) => sum + ms) / values.length).toFixed(2) + ' ms',
250
+ min: Math.min(...values).toFixed(2) + ' ms',
251
+ max: Math.max(...values).toFixed(2) + ' ms'
252
+ };
253
+ return result;
254
+ }
255
+
256
+
257
+ /* Returns s converted to an integer, but only if it falls into the acceptable range */
258
+
259
+ static parseIntRange(s, min, max) {
260
+ if (isNaN(+s))
261
+ return null;
262
+ const n = Math.round(+s);
263
+ if (n < min || n > max)
264
+ return null;
265
+ return n;
266
+ }
267
+
268
+
269
+ /* Round the number to given number of decimals. */
270
+
271
+ static round(number, decimals = 0) {
272
+ const multiplier = Math.pow(10, decimals);
273
+ return Math.round(number * multiplier) / multiplier;
274
+ }
275
+
276
+
277
+ /* Round the fractional part of a number so that the number has at least the given
278
+ number of significant digits.
279
+
280
+ The integer part is not rounded, however. So (123.45, 4) --> 123.5, but (12345, 4) --> 12345. */
281
+
282
+ static roundPrecision(number, significantDigits) {
283
+ return Util.round(
284
+ number,
285
+ Number(number) === 0 ?
286
+ significantDigits :
287
+ Math.max(0, significantDigits - Math.floor(Math.log10(number) + 1))
288
+ );
289
+ }
290
+
291
+
292
+ /* Return the given number value in string format in the given locale, or the string "NaN"
293
+ if the value cannot be converted to number.
294
+
295
+ Thousand separators are used, with the minimum value given as an optional parameter.
296
+
297
+ If the optional parameter "signed" is set to true, positive values will also be signed.
298
+ Positive and negative zero never has a sign, however.
299
+
300
+ Negative values are always returned with the minus sign as the character. Note that this
301
+ alone will prevent the return value to be used as a number.
302
+
303
+ By default the number of is rounded to zero decimals. If the option "decimals" is a number
304
+ then a fixed number of decimals are used, including possible trailing zeros. The option
305
+ "decimals" can also be a two-element array that gives the minimum and maximum number of
306
+ fraction digits. */
307
+
308
+ static formatNumber(value, {
309
+ locale = 'en',
310
+ signed = false,
311
+ separatorMin = 1000,
312
+ decimals = 0
313
+ } = {}) {
314
+
315
+ const number = Number(value);
316
+
317
+ /* Value cannot be converted to a number -- this is likely an accident? */
318
+ if (Number.isNaN(number)) {
319
+ console.warn('Cannot format number', value);
320
+ return String(NaN);
321
+ }
322
+
323
+ const options = {
324
+ /* Add thousand separators if value is big/small enough */
325
+ useGrouping: Math.abs(number) >= separatorMin,
326
+ signDisplay: signed ? 'exceptZero' : 'negative'
327
+ };
328
+
329
+ if (decimals instanceof Array) {
330
+ options.minimumFractionDigits = decimals[0];
331
+ options.maximumFractionDigits = decimals[1];
332
+ } else if (typeof decimals === 'number' ) {
333
+ options.minimumFractionDigits = decimals;
334
+ options.maximumFractionDigits = decimals;
335
+ }
336
+
337
+ /* Localized to string */
338
+ const localized = number.toLocaleString(locale, options);
339
+
340
+ /* Finally, replace possible hyphen-minus with a minus sign */
341
+ return localized[0] === '-' ?
342
+ ('\u2212' + localized.slice(1)) :
343
+ localized;
344
+ }
345
+
346
+
347
+ /* Format number of seconds to either like "40 or like "1:40". */
348
+
349
+ static formatSeconds(seconds) {
350
+ if (seconds <= 60)
351
+ return Math.round(seconds);
352
+ else
353
+ return Math.floor(seconds / 60) + ':' + (Math.round(seconds) % 60).toString().padStart(2, '0');
354
+ }
355
+
356
+
357
+ /* Convert integer to roman numerals.
358
+
359
+ https://stackoverflow.com/a/56444611 */
360
+
361
+ static toRoman(int) {
362
+ let roman = '';
363
+ roman += 'M'.repeat(int / 1000); int %= 1000;
364
+ roman += 'CM'.repeat(int / 900); int %= 900;
365
+ roman += 'D'.repeat(int / 500); int %= 500;
366
+ roman += 'CD'.repeat(int / 400); int %= 400;
367
+ roman += 'C'.repeat(int / 100); int %= 100;
368
+ roman += 'XC'.repeat(int / 90); int %= 90;
369
+ roman += 'L'.repeat(int / 50); int %= 50;
370
+ roman += 'XL'.repeat(int / 40); int %= 40;
371
+ roman += 'X'.repeat(int / 10); int %= 10;
372
+ roman += 'IX'.repeat(int / 9); int %= 9;
373
+ roman += 'V'.repeat(int / 5); int %= 5;
374
+ roman += 'IV'.repeat(int / 4); int %= 4;
375
+ roman += 'I'.repeat(int);
376
+ return roman;
377
+ }
378
+
379
+
380
+ /* Like the Bash built-in command: Return an array of integers from start to end.
381
+
382
+ Note: Step can be negative, or non-integer. */
383
+
384
+ static seq(start, end, step = 1) {
385
+ const result = [];
386
+ for (let value = start; step > 0 ? value <= end : value >= end; value += step)
387
+ result.push(value);
388
+ return result;
389
+ }
390
+
391
+
392
+ /* Return an array of [ minValue, maxValue ] for the given array.
393
+
394
+ If the array has only one value, then return the array is returned. */
395
+
396
+ static minMax(array) {
397
+ if (array.length > 1)
398
+ return [Math.min(...array), Math.max(...array)];
399
+ else
400
+ return array;
401
+ }
402
+
403
+
404
+ /* Write log messages with a time in milliseconds elapsed since window.ST_TIMELINE_START that should be stored
405
+ at the earliest possible moment in the first <script> element of <head>. */
406
+
407
+ static logTimeline(message, { devel = false } = {}) {
408
+
409
+ /* If window.ST_TIMELINE_START is not set, set it on first call */
410
+
411
+ if (!window.ST_TIMELINE_START) {
412
+ console.info('Initializing window.ST_TIMELINE_START as it is not set');
413
+ window.ST_TIMELINE_START = Date.now();
414
+ }
415
+
416
+ if (devel && !Util.envDevelopment)
417
+ return;
418
+
419
+ console.info(
420
+ `%c<< ${Date.now() - +window.ST_TIMELINE_START} ms >> ${message}`,
421
+ `font-weight: ${devel ? 'normal' : 'bold'}; font-size: 1.1em;`
422
+ );
423
+ }
424
+
425
+
426
+ /* Like Python's zip(): Return an array of arrays from a set of iterables. Each item of the
427
+ returned array is an array of values of the iterables.
428
+
429
+ For example: ['a', 'b', 'c'], [1, 2] => [['a', 1], ['b', 2], ['c', undefined]] */
430
+
431
+ static zip(...args) {
432
+ const iterators = args.map(arg => arg[Symbol.iterator]());
433
+ const result = [];
434
+
435
+ let done = false;
436
+ while (!done) {
437
+ const a = [];
438
+ done = true;
439
+ for (const iterator of iterators) {
440
+ const next = iterator.next();
441
+ a.push(next.value);
442
+ if (!next.done)
443
+ done = false;
444
+ }
445
+ if (!done)
446
+ result.push(a);
447
+ }
448
+
449
+ return result;
450
+ }
451
+
452
+
453
+ /* Compare two version numbers. If versions have unequal number of components,
454
+ the one with fewer components is considered earlier, e.g. 1.2 is before 1.2.0.
455
+
456
+ By default any number of components are considered in the version number, but
457
+ this can be limited by providing the third parameter maxComponents. */
458
+
459
+ static versionCompare(
460
+ version1,
461
+ version2,
462
+ {
463
+ maxComponents = Number.MAX_VALUE,
464
+ skipLeadingZeros = false
465
+ } = {}
466
+ ) {
467
+
468
+ let
469
+ components1 = version1.split('.'),
470
+ components2 = version2.split('.');
471
+
472
+ if (skipLeadingZeros) {
473
+ components1 = components1.slice(components1.findIndex(n => n !== '0'));
474
+ components2 = components2.slice(components2.findIndex(n => n !== '0'));
475
+ }
476
+
477
+ for (const [num1, num2] of Util.zip(components1, components2).slice(0, maxComponents)) {
478
+ if (!num1)
479
+ return -1;
480
+ if (!num2)
481
+ return 1;
482
+ const diff = +num1 - +num2;
483
+ if (diff)
484
+ return diff;
485
+ }
486
+ return 0;
487
+ }
488
+
489
+
490
+ /* Calculate a new version number from a version number an offset.
491
+
492
+ Positive offset returns an older version, negative offset a newer version. */
493
+
494
+ static #versionCalculate(version, offset) {
495
+ const [, major, minor] = version.match(/^[0-9]+\.([0-9]+)\.([0-9]+)/);
496
+ const oldVersion = Number(major) * 12 + Number(minor) - Number(offset);
497
+ return `0.${Math.floor(oldVersion / 12)}.${oldVersion % 12}`;
498
+ }
499
+
500
+ static versionEarlier(version, offset) {
501
+ return Util.#versionCalculate(version, offset);
502
+ }
503
+
504
+ static versionLater(version, offset) {
505
+ return Util.#versionCalculate(version, -offset);
506
+ }
507
+
508
+
509
+ /* Adjust an array of numbers so that all numbers have at least the given
510
+ numerical distance. For example ( [1, 2], 2 ) returns [ 0.5, 2.5 ].
511
+
512
+ The returned array has the corresponding order of values.
513
+
514
+ TODO: Configurable handling for duplicate values? Currently they are also spaced out. */
515
+
516
+ static distNumbers(src, dist) {
517
+
518
+ /* Shift integer value at the given index by the given amount.
519
+
520
+ Once done, check if the next value in the direction of the shift is now
521
+ too close. If it is, recursively shift it either the same amount or to
522
+ the minimum distance, whichever is less. */
523
+
524
+ const move = (j, shift) => {
525
+ a[j].n += shift;
526
+ if (shift > 0 && j + 1 in a) {
527
+ const spread = dist - (a[j + 1].n - a[j].n);
528
+ if (spread > 0)
529
+ move(j + 1, Math.min(spread, shift));
530
+ }
531
+ if (shift < 0 && j - 1 in a) {
532
+ const spread = dist - (a[j].n - a[j - 1].n);
533
+ if (spread > 0)
534
+ move(j - 1, Math.max(-spread, shift));
535
+ }
536
+ };
537
+
538
+ /* Sort the array to numerical order, replacing each number with an object
539
+ that also contains its original index. */
540
+
541
+ const a = src.map((n, i) => ({ n, i })).sort((n, m) => n.n - m.n);
542
+
543
+ /* Scan the array, and if any two numbers are too close, shift their values
544
+ equally away from each other to have the minimum distance. */
545
+
546
+ for (let i = 1; i < a.length; i++) {
547
+ const spread = dist - (a[i].n - a[i - 1].n);
548
+ if (spread > 0) {
549
+ move(i, spread / 2);
550
+ move(i - 1, -spread / 2);
551
+ }
552
+ }
553
+
554
+ /* Return the adjusted numbers in the original order */
555
+
556
+ return a.sort((n, m) => n.i - m.i).map(n => n.n);
557
+ }
558
+
559
+
560
+ static arrayIntersection(...arrays) {
561
+
562
+ /* Recursively intersect two or more arrays */
563
+ const doIntersection = (...arrays) => {
564
+ const set = new Set(arrays[1]);
565
+ const intersection = arrays[0].filter(value => set.has(value));
566
+ if (arrays.length > 2)
567
+ return doIntersection(intersection, ...arrays.slice(2));
568
+ else
569
+ return intersection;
570
+ };
571
+
572
+ if (arrays.length === 0)
573
+ return [];
574
+ else if (arrays.length === 1)
575
+ return [...arrays[0]];
576
+ else
577
+ return doIntersection(...arrays);
578
+ }
579
+
580
+
581
+ static arrayUnion(...arrays) {
582
+
583
+ /* Recursively make a union of two or more arrays */
584
+ const doUnion = (...arrays) => {
585
+ const set = new Set(arrays[0]);
586
+ const union = [...arrays[0], ...arrays[1].filter(value => !set.has(value))];
587
+ if (arrays.length > 2)
588
+ return doUnion(union, ...arrays.slice(2));
589
+ else
590
+ return union;
591
+ };
592
+
593
+ if (arrays.length === 0)
594
+ return [];
595
+ else if (arrays.length === 1)
596
+ return [...arrays[0]];
597
+ else
598
+ return doUnion(...arrays);
599
+ }
600
+
601
+
602
+ static arrayDifference(...arrays) {
603
+
604
+ /* Recursively make a difference of two or more arrays */
605
+ const doDifference = (...arrays) => {
606
+ const set = new Set(arrays[1]);
607
+ const difference = arrays[0].filter(value => !set.has(value));
608
+ if (arrays.length > 2)
609
+ return doDifference(difference, ...arrays.slice(2));
610
+ else
611
+ return difference;
612
+ };
613
+
614
+ if (arrays.length === 0)
615
+ return [];
616
+ else if (arrays.length === 1)
617
+ return [...arrays[0]];
618
+ else
619
+ return doDifference(...arrays);
620
+ }
621
+
622
+
623
+ /* Compare two arrays, returning an array of three arrays:
624
+
625
+ 1. Array of values included only in A
626
+ 2. Array of values included in both A and B
627
+ 3. Array of values included only in B
628
+
629
+ The result is the same as [arrayDifference(A, B), arrayIntersection(A, B), arrayDifference(B, A)],
630
+ but this implementation should be a little bit faster because only two arrays are supported.
631
+
632
+ Warning: Duplicate values are not handled consistently. Duplicates included only in one of the
633
+ arrays are retained, but if included in both only duplicates of A are retained. */
634
+
635
+ static arrayCompare(a, b) {
636
+ const onlyA = [];
637
+ const onlyB = [];
638
+ const both = [];
639
+ const aSet = new Set(a);
640
+ const bSet = new Set(b);
641
+ for (const aValue of a)
642
+ if (bSet.has(aValue))
643
+ both.push(aValue);
644
+ else
645
+ onlyA.push(aValue);
646
+ for (const bValue of b)
647
+ if (!aSet.has(bValue))
648
+ onlyB.push(bValue);
649
+ return [onlyA, both, onlyB];
650
+ }
651
+
652
+
653
+ /* Split array into chunks of the given size. Last chunk may be shorter. */
654
+
655
+ static arrayChunks(a, chunkSize) {
656
+ const result = [];
657
+ for (let i = 0; i < a.length; i += chunkSize)
658
+ result.push(a.slice(i, i + chunkSize));
659
+ return result;
660
+ }
661
+
662
+
663
+ /* Split array into equal-sized chunks of at most the given size. All chunks
664
+ may be shorter than the maximum size, and last chunk may be shorter than others.
665
+
666
+ As an example, if an array of length 9 is split to chunks of maximum length 4,
667
+ three arrays of length 3 are returned. */
668
+
669
+ static arrayChunksEqual(a, maxChunkSize) {
670
+ const noChunks = Math.ceil(a.length / maxChunkSize);
671
+ const chunkSize = Math.ceil(a.length / noChunks);
672
+ return Util.arrayChunks(a, chunkSize);
673
+ }
674
+
675
+
676
+ /* Return the prototype chain of an object as an array of constructor names */
677
+
678
+ static getPrototypeChain(o) {
679
+ const result = [];
680
+ let p = Object.getPrototypeOf(o);
681
+ while(p) {
682
+ result.push(p.constructor.name);
683
+ p = Object.getPrototypeOf(p);
684
+ }
685
+ return result;
686
+ }
687
+
688
+
689
+ /* Linear regression using least squares method.
690
+
691
+ Adapted from: https://stackoverflow.com/a/31566791
692
+
693
+ Currently only slope is used so the rest have been commented. */
694
+
695
+ static linearRegression(y, x) {
696
+ const n = y.length;
697
+ let sumX = 0;
698
+ let sumY = 0;
699
+ let sumXY = 0;
700
+ let sumXX = 0;
701
+ // let sumYY = 0;
702
+
703
+ for (let i = 0; i < n; i++) {
704
+ sumX += x[i];
705
+ sumY += y[i];
706
+ sumXY += x[i] * y[i];
707
+ sumXX += x[i] ** 2;
708
+ // sumYY += y[i] ** 2;
709
+ }
710
+
711
+ const slope = (n * sumXY - sumX * sumY) / (n * sumXX - sumX ** 2);
712
+ // const intercept = (sumY - slope * sumX) / n;
713
+ // const r2 = ((n * sumXY - sumX * sumY) / Math.sqrt((n * sumXX - sumX ** 2) * (n * sumYY - sumY ** 2))) ** 2;
714
+
715
+ return {
716
+ slope,
717
+ // intercept,
718
+ // r2
719
+ };
720
+ }
721
+
722
+
723
+ static camelToUpperCase(s) {
724
+ return s.replaceAll(/[A-Z]/g, (match, offset) => (offset > 0 ? '_' : '') + match).toUpperCase();
725
+ }
726
+
727
+ static camelToLowerCase(s) {
728
+ return s.replaceAll(/[A-Z]/g, (match, offset) => (offset > 0 ? '_' : '') + match).toLowerCase();
729
+ }
730
+
731
+
732
+ static #tableColumns;
733
+ static #tableLogger;
734
+ static #tableRule;
735
+
736
+ static tableStart(columns, { logger = null } = {}) {
737
+ Util.#tableColumns = columns.map(({ name, width, right }) => ({
738
+ width: width || name.length,
739
+ right
740
+ }));
741
+ Util.#tableLogger = logger || console.log;
742
+ Util.#tableRule = '-'.repeat(columns.reduce((sum, { width }) => sum + width, 0) + columns.length - 1);
743
+ Util.#tableLogger(Util.#tableRule);
744
+ Util.tableRow(...columns.map(({ name }) => name));
745
+ Util.#tableLogger(Util.#tableRule);
746
+ }
747
+
748
+ static tableRow(...values) {
749
+ Util.#tableLogger(values.map((value, i) =>
750
+ Util.#tableColumns[i].right ?
751
+ String(value).padEnd(Util.#tableColumns[i].width) :
752
+ String(value).padStart(Util.#tableColumns[i].width)
753
+ ).join(' '));
754
+ }
755
+
756
+ static tableEnd() {
757
+ Util.#tableLogger(Util.#tableRule);
758
+ }
759
+
760
+
761
+ /* Asynchronous intervals, adapted from: https://dev.to/jsmccrumb/asynchronous-setinterval-4j69 */
762
+
763
+ static #asyncIntervals = [];
764
+
765
+ static async #runAsyncInterval(callback, interval, intervalIndex) {
766
+ await callback();
767
+ if (Util.#asyncIntervals[intervalIndex])
768
+ setTimeout(() => Util.#runAsyncInterval(callback, interval, intervalIndex), interval);
769
+ }
770
+
771
+ static setAsyncInterval(callback, interval) {
772
+ if (typeof callback === 'function') {
773
+ const intervalIndex = Util.#asyncIntervals.length;
774
+ Util.#asyncIntervals.push(true);
775
+ Util.#runAsyncInterval(callback, interval, intervalIndex);
776
+ return intervalIndex;
777
+ } else {
778
+ throw new Error('Callback must be a function');
779
+ }
780
+ }
781
+
782
+ static clearAsyncInterval(intervalIndex) {
783
+ if (Util.#asyncIntervals[intervalIndex])
784
+ Util.#asyncIntervals[intervalIndex] = false;
785
+ }
786
+ }
787
+
788
+
789
+ export default Util;