@antti5/ship-tool-common 1.1.0 → 1.1.1
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 → Util.ts} +127 -179
- package/lib/{UtilNode.js → UtilNode.ts} +30 -22
- package/package.json +5 -3
- package/tsconfig.json +1 -12
package/lib/{Util.js → Util.ts}
RENAMED
|
@@ -5,7 +5,7 @@ class Util {
|
|
|
5
5
|
The executor function given to the Promise constructor simply sets a timeout to call
|
|
6
6
|
the resolve function. The Promise is never rejected. */
|
|
7
7
|
|
|
8
|
-
static async sleep(ms) {
|
|
8
|
+
static async sleep(ms: number) {
|
|
9
9
|
await new Promise(res => setTimeout(res, ms));
|
|
10
10
|
}
|
|
11
11
|
|
|
@@ -26,25 +26,34 @@ class Util {
|
|
|
26
26
|
is thrown. The error message contains the HTTP status text and code, and the "cause" property
|
|
27
27
|
contains the Window.fetch() response object. */
|
|
28
28
|
|
|
29
|
-
static #fetchResponse = {};
|
|
29
|
+
static #fetchResponse: Record<string, { body: unknown, timestamp: number }> = {};
|
|
30
30
|
|
|
31
|
-
static async fetch (
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
31
|
+
static async fetch (
|
|
32
|
+
url: string,
|
|
33
|
+
{
|
|
34
|
+
urlSearchParams,
|
|
35
|
+
method = 'GET',
|
|
36
|
+
body,
|
|
37
|
+
headers = {},
|
|
38
|
+
timeout,
|
|
39
|
+
debug
|
|
40
|
+
}: {
|
|
41
|
+
urlSearchParams: Record<string,string>,
|
|
42
|
+
method: string,
|
|
43
|
+
body: unknown,
|
|
44
|
+
headers: Record<string,string>,
|
|
45
|
+
timeout: number,
|
|
46
|
+
debug: boolean
|
|
47
|
+
}
|
|
48
|
+
) {
|
|
39
49
|
|
|
40
50
|
if (urlSearchParams)
|
|
41
|
-
url += '?' + new URLSearchParams(urlSearchParams);
|
|
51
|
+
url += '?' + new URLSearchParams(urlSearchParams).toString();
|
|
42
52
|
|
|
43
|
-
const cacheMs =
|
|
53
|
+
const cacheMs =
|
|
44
54
|
typeof process !== 'undefined' ?
|
|
45
|
-
process.env
|
|
46
|
-
|
|
47
|
-
);
|
|
55
|
+
Number(process.env.VITE_FETCH_CACHE_MS) : // Vitest
|
|
56
|
+
null;
|
|
48
57
|
|
|
49
58
|
if (cacheMs && Util.#fetchResponse[url]?.timestamp + cacheMs > Date.now()) {
|
|
50
59
|
console.debug('Returning cached response for URL', url);
|
|
@@ -76,7 +85,7 @@ class Util {
|
|
|
76
85
|
|
|
77
86
|
const responseBody =
|
|
78
87
|
response.headers.get('Content-Type')?.includes('application/json') ?
|
|
79
|
-
await response.json() :
|
|
88
|
+
await response.json() as unknown :
|
|
80
89
|
await response.text(); // If response isn't JSON, return a String instead -- TODO: This may be a poor design
|
|
81
90
|
|
|
82
91
|
if (debug)
|
|
@@ -93,44 +102,10 @@ class Util {
|
|
|
93
102
|
return responseBody;
|
|
94
103
|
}
|
|
95
104
|
|
|
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
105
|
|
|
131
106
|
/* Generated random numbers and index for the next number */
|
|
132
107
|
|
|
133
|
-
static #randoms = [];
|
|
108
|
+
static #randoms: number[] = [];
|
|
134
109
|
static #randomsIndex = 0;
|
|
135
110
|
|
|
136
111
|
/* Get a random number, either from the #randoms array or create and store a new one */
|
|
@@ -148,51 +123,9 @@ class Util {
|
|
|
148
123
|
}
|
|
149
124
|
|
|
150
125
|
|
|
151
|
-
static perfObject(key) {
|
|
152
|
-
window.ST_PERF ??= {};
|
|
153
|
-
window.ST_PERF[key] ??= [];
|
|
154
|
-
return window.ST_PERF[key];
|
|
155
|
-
}
|
|
156
|
-
|
|
157
|
-
static perfStart() {
|
|
158
|
-
return performance.now();
|
|
159
|
-
}
|
|
160
|
-
|
|
161
|
-
static perfEndMany(count, startTime, key, { log } = {}) {
|
|
162
|
-
const ms = performance.now() - startTime;
|
|
163
|
-
const o = Util.perfObject(key);
|
|
164
|
-
|
|
165
|
-
for (let i = 0; i < count; i++)
|
|
166
|
-
o.push(ms / count);
|
|
167
|
-
|
|
168
|
-
if (log) {
|
|
169
|
-
console.debug('Performance:', `${count}x`, key, Util.round(ms / count, 2), 'ms');
|
|
170
|
-
if (count > 1)
|
|
171
|
-
console.debug('Performance: Total:', Util.round(ms, 2), 'ms');
|
|
172
|
-
}
|
|
173
|
-
}
|
|
174
|
-
|
|
175
|
-
static perfEnd(...args) {
|
|
176
|
-
return Util.perfEndMany(1, ...args);
|
|
177
|
-
}
|
|
178
|
-
|
|
179
|
-
static perfReport() {
|
|
180
|
-
const result = {};
|
|
181
|
-
for (const [key, values] of Object.entries(window.ST_PERF ?? {}))
|
|
182
|
-
result[key] = {
|
|
183
|
-
count: values.length,
|
|
184
|
-
total: values.reduce((sum, ms) => sum + ms).toFixed(2) + ' ms',
|
|
185
|
-
avg: (values.reduce((sum, ms) => sum + ms) / values.length).toFixed(2) + ' ms',
|
|
186
|
-
min: Math.min(...values).toFixed(2) + ' ms',
|
|
187
|
-
max: Math.max(...values).toFixed(2) + ' ms'
|
|
188
|
-
};
|
|
189
|
-
return result;
|
|
190
|
-
}
|
|
191
|
-
|
|
192
|
-
|
|
193
126
|
/* Returns s converted to an integer, but only if it falls into the acceptable range */
|
|
194
127
|
|
|
195
|
-
static parseIntRange(s, min, max) {
|
|
128
|
+
static parseIntRange(s: string, min: number, max: number) {
|
|
196
129
|
if (isNaN(+s))
|
|
197
130
|
return null;
|
|
198
131
|
const n = Math.round(+s);
|
|
@@ -204,7 +137,7 @@ class Util {
|
|
|
204
137
|
|
|
205
138
|
/* Round the number to given number of decimals. */
|
|
206
139
|
|
|
207
|
-
static round(number, decimals = 0) {
|
|
140
|
+
static round(number: number, decimals: number = 0) {
|
|
208
141
|
const multiplier = Math.pow(10, decimals);
|
|
209
142
|
return Math.round(number * multiplier) / multiplier;
|
|
210
143
|
}
|
|
@@ -215,7 +148,7 @@ class Util {
|
|
|
215
148
|
|
|
216
149
|
The integer part is not rounded, however. So (123.45, 4) --> 123.5, but (12345, 4) --> 12345. */
|
|
217
150
|
|
|
218
|
-
static roundPrecision(number, significantDigits) {
|
|
151
|
+
static roundPrecision(number: number, significantDigits: number) {
|
|
219
152
|
return Util.round(
|
|
220
153
|
number,
|
|
221
154
|
Number(number) === 0 ?
|
|
@@ -241,12 +174,20 @@ class Util {
|
|
|
241
174
|
"decimals" can also be a two-element array that gives the minimum and maximum number of
|
|
242
175
|
fraction digits. */
|
|
243
176
|
|
|
244
|
-
static formatNumber(
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
|
|
249
|
-
|
|
177
|
+
static formatNumber(
|
|
178
|
+
value: unknown,
|
|
179
|
+
{
|
|
180
|
+
locale = 'en',
|
|
181
|
+
signed = false,
|
|
182
|
+
separatorMin = 1000,
|
|
183
|
+
decimals = 0
|
|
184
|
+
}: {
|
|
185
|
+
locale?: string,
|
|
186
|
+
signed?: boolean,
|
|
187
|
+
separatorMin?: number,
|
|
188
|
+
decimals?: number | number[]
|
|
189
|
+
} = {}
|
|
190
|
+
) {
|
|
250
191
|
|
|
251
192
|
const number = Number(value);
|
|
252
193
|
|
|
@@ -256,7 +197,7 @@ class Util {
|
|
|
256
197
|
return String(NaN);
|
|
257
198
|
}
|
|
258
199
|
|
|
259
|
-
const options = {
|
|
200
|
+
const options: Intl.NumberFormatOptions = {
|
|
260
201
|
/* Add thousand separators if value is big/small enough */
|
|
261
202
|
useGrouping: Math.abs(number) >= separatorMin,
|
|
262
203
|
signDisplay: signed ? 'exceptZero' : 'auto'
|
|
@@ -297,7 +238,7 @@ class Util {
|
|
|
297
238
|
|
|
298
239
|
/* Format number of seconds to either like "40 or like "1:40". */
|
|
299
240
|
|
|
300
|
-
static formatSeconds(seconds) {
|
|
241
|
+
static formatSeconds(seconds: number) {
|
|
301
242
|
if (seconds <= 60)
|
|
302
243
|
return Math.round(seconds);
|
|
303
244
|
else
|
|
@@ -309,21 +250,21 @@ class Util {
|
|
|
309
250
|
|
|
310
251
|
https://stackoverflow.com/a/56444611 */
|
|
311
252
|
|
|
312
|
-
static toRoman(
|
|
253
|
+
static toRoman(integer: number) {
|
|
313
254
|
let roman = '';
|
|
314
|
-
roman += 'M'.repeat(
|
|
315
|
-
roman += 'CM'.repeat(
|
|
316
|
-
roman += 'D'.repeat(
|
|
317
|
-
roman += 'CD'.repeat(
|
|
318
|
-
roman += 'C'.repeat(
|
|
319
|
-
roman += 'XC'.repeat(
|
|
320
|
-
roman += 'L'.repeat(
|
|
321
|
-
roman += 'XL'.repeat(
|
|
322
|
-
roman += 'X'.repeat(
|
|
323
|
-
roman += 'IX'.repeat(
|
|
324
|
-
roman += 'V'.repeat(
|
|
325
|
-
roman += 'IV'.repeat(
|
|
326
|
-
roman += 'I'.repeat(
|
|
255
|
+
roman += 'M'.repeat(integer / 1000); integer %= 1000;
|
|
256
|
+
roman += 'CM'.repeat(integer / 900); integer %= 900;
|
|
257
|
+
roman += 'D'.repeat(integer / 500); integer %= 500;
|
|
258
|
+
roman += 'CD'.repeat(integer / 400); integer %= 400;
|
|
259
|
+
roman += 'C'.repeat(integer / 100); integer %= 100;
|
|
260
|
+
roman += 'XC'.repeat(integer / 90); integer %= 90;
|
|
261
|
+
roman += 'L'.repeat(integer / 50); integer %= 50;
|
|
262
|
+
roman += 'XL'.repeat(integer / 40); integer %= 40;
|
|
263
|
+
roman += 'X'.repeat(integer / 10); integer %= 10;
|
|
264
|
+
roman += 'IX'.repeat(integer / 9); integer %= 9;
|
|
265
|
+
roman += 'V'.repeat(integer / 5); integer %= 5;
|
|
266
|
+
roman += 'IV'.repeat(integer / 4); integer %= 4;
|
|
267
|
+
roman += 'I'.repeat(integer);
|
|
327
268
|
return roman;
|
|
328
269
|
}
|
|
329
270
|
|
|
@@ -332,7 +273,7 @@ class Util {
|
|
|
332
273
|
|
|
333
274
|
Note: Step can be negative, or non-integer. */
|
|
334
275
|
|
|
335
|
-
static seq(start, end, step = 1) {
|
|
276
|
+
static seq(start: number, end: number, step = 1) {
|
|
336
277
|
const result = [];
|
|
337
278
|
for (let value = start; step > 0 ? value <= end : value >= end; value += step)
|
|
338
279
|
result.push(value);
|
|
@@ -344,7 +285,7 @@ class Util {
|
|
|
344
285
|
|
|
345
286
|
If the array has only one value, then return the array is returned. */
|
|
346
287
|
|
|
347
|
-
static minMax(array) {
|
|
288
|
+
static minMax(array: number[]) {
|
|
348
289
|
if (array.length > 1)
|
|
349
290
|
return [Math.min(...array), Math.max(...array)];
|
|
350
291
|
else
|
|
@@ -352,34 +293,12 @@ class Util {
|
|
|
352
293
|
}
|
|
353
294
|
|
|
354
295
|
|
|
355
|
-
/* Write log messages with a time in milliseconds elapsed since window.ST_TIMELINE_START that should be stored
|
|
356
|
-
at the earliest possible moment in the first <script> element of <head>. */
|
|
357
|
-
|
|
358
|
-
static logTimeline(message, { devel = false } = {}) {
|
|
359
|
-
|
|
360
|
-
/* If window.ST_TIMELINE_START is not set, set it on first call */
|
|
361
|
-
|
|
362
|
-
if (!window.ST_TIMELINE_START) {
|
|
363
|
-
console.info('Initializing window.ST_TIMELINE_START as it is not set');
|
|
364
|
-
window.ST_TIMELINE_START = Date.now();
|
|
365
|
-
}
|
|
366
|
-
|
|
367
|
-
if (devel && !Util.envDevelopment)
|
|
368
|
-
return;
|
|
369
|
-
|
|
370
|
-
console.info(
|
|
371
|
-
`%c<< ${Date.now() - +window.ST_TIMELINE_START} ms >> ${message}`,
|
|
372
|
-
`font-weight: ${devel ? 'normal' : 'bold'}; font-size: 1.1em;`
|
|
373
|
-
);
|
|
374
|
-
}
|
|
375
|
-
|
|
376
|
-
|
|
377
296
|
/* Like Python's zip(): Return an array of arrays from a set of iterables. Each item of the
|
|
378
297
|
returned array is an array of values of the iterables.
|
|
379
298
|
|
|
380
299
|
For example: ['a', 'b', 'c'], [1, 2] => [['a', 1], ['b', 2], ['c', undefined]] */
|
|
381
300
|
|
|
382
|
-
static zip(...args) {
|
|
301
|
+
static zip(...args: unknown[][]) {
|
|
383
302
|
const iterators = args.map(arg => arg[Symbol.iterator]());
|
|
384
303
|
const result = [];
|
|
385
304
|
|
|
@@ -408,8 +327,8 @@ class Util {
|
|
|
408
327
|
this can be limited by providing the third parameter maxComponents. */
|
|
409
328
|
|
|
410
329
|
static versionCompare(
|
|
411
|
-
version1,
|
|
412
|
-
version2,
|
|
330
|
+
version1: string,
|
|
331
|
+
version2: string,
|
|
413
332
|
{
|
|
414
333
|
maxComponents = Number.MAX_VALUE,
|
|
415
334
|
skipLeadingZeros = false
|
|
@@ -442,17 +361,26 @@ class Util {
|
|
|
442
361
|
|
|
443
362
|
Positive offset returns an older version, negative offset a newer version. */
|
|
444
363
|
|
|
445
|
-
static #versionCalculate(version, offset) {
|
|
446
|
-
const
|
|
447
|
-
|
|
448
|
-
|
|
364
|
+
static #versionCalculate(version: string, offset: number) {
|
|
365
|
+
const versionMatch: RegExpMatchArray | null = version.match(/^[0-9]+\.([0-9]+)\.([0-9]+)/);
|
|
366
|
+
|
|
367
|
+
if (versionMatch?.length === 3) {
|
|
368
|
+
const [, major, minor] = versionMatch;
|
|
369
|
+
const oldVersion = Number(major) * 12 + Number(minor) - Number(offset);
|
|
370
|
+
return `0.${Math.floor(oldVersion / 12)}.${oldVersion % 12}`;
|
|
371
|
+
} else
|
|
372
|
+
throw new Error('Invalid version: ' + version);
|
|
449
373
|
}
|
|
450
374
|
|
|
451
|
-
|
|
375
|
+
/* Calculate earlier version */
|
|
376
|
+
|
|
377
|
+
static versionEarlier(version: string, offset: number) {
|
|
452
378
|
return Util.#versionCalculate(version, offset);
|
|
453
379
|
}
|
|
454
380
|
|
|
455
|
-
|
|
381
|
+
/* Calculate later version */
|
|
382
|
+
|
|
383
|
+
static versionLater(version: string, offset: number) {
|
|
456
384
|
return Util.#versionCalculate(version, -offset);
|
|
457
385
|
}
|
|
458
386
|
|
|
@@ -464,7 +392,7 @@ class Util {
|
|
|
464
392
|
|
|
465
393
|
TODO: Configurable handling for duplicate values? Currently they are also spaced out. */
|
|
466
394
|
|
|
467
|
-
static distNumbers(src, dist) {
|
|
395
|
+
static distNumbers(src: number[], dist: number) {
|
|
468
396
|
|
|
469
397
|
/* Shift integer value at the given index by the given amount.
|
|
470
398
|
|
|
@@ -472,7 +400,7 @@ class Util {
|
|
|
472
400
|
too close. If it is, recursively shift it either the same amount or to
|
|
473
401
|
the minimum distance, whichever is less. */
|
|
474
402
|
|
|
475
|
-
const move = (j, shift) => {
|
|
403
|
+
const move = (j: number, shift: number) => {
|
|
476
404
|
a[j].n += shift;
|
|
477
405
|
if (shift > 0 && j + 1 in a) {
|
|
478
406
|
const spread = dist - (a[j + 1].n - a[j].n);
|
|
@@ -508,10 +436,12 @@ class Util {
|
|
|
508
436
|
}
|
|
509
437
|
|
|
510
438
|
|
|
511
|
-
|
|
439
|
+
/* Intersection of two or more arrays */
|
|
440
|
+
|
|
441
|
+
static arrayIntersection(...arrays: unknown[][]) {
|
|
512
442
|
|
|
513
|
-
|
|
514
|
-
const doIntersection = (...arrays) => {
|
|
443
|
+
// Recursive worker to handle two arrays at a time
|
|
444
|
+
const doIntersection = (...arrays: unknown[][]) => {
|
|
515
445
|
const set = new Set(arrays[1]);
|
|
516
446
|
const intersection = arrays[0].filter(value => set.has(value));
|
|
517
447
|
if (arrays.length > 2)
|
|
@@ -528,11 +458,12 @@ class Util {
|
|
|
528
458
|
return doIntersection(...arrays);
|
|
529
459
|
}
|
|
530
460
|
|
|
461
|
+
/* Intersection of two or more arrays */
|
|
531
462
|
|
|
532
|
-
static arrayUnion(...arrays) {
|
|
463
|
+
static arrayUnion(...arrays: unknown[][]) {
|
|
533
464
|
|
|
534
|
-
|
|
535
|
-
const doUnion = (...arrays) => {
|
|
465
|
+
// Recursive worker to handle two arrays at a time
|
|
466
|
+
const doUnion = (...arrays: unknown[][]) => {
|
|
536
467
|
const set = new Set(arrays[0]);
|
|
537
468
|
const union = [...arrays[0], ...arrays[1].filter(value => !set.has(value))];
|
|
538
469
|
if (arrays.length > 2)
|
|
@@ -549,11 +480,12 @@ class Util {
|
|
|
549
480
|
return doUnion(...arrays);
|
|
550
481
|
}
|
|
551
482
|
|
|
483
|
+
/* Difference of two or more arrays */
|
|
552
484
|
|
|
553
|
-
static arrayDifference(...arrays) {
|
|
485
|
+
static arrayDifference(...arrays: unknown[][]) {
|
|
554
486
|
|
|
555
|
-
|
|
556
|
-
const doDifference = (...arrays) => {
|
|
487
|
+
// Recursive worker to handle two arrays at a time
|
|
488
|
+
const doDifference = (...arrays: unknown[][]) => {
|
|
557
489
|
const set = new Set(arrays[1]);
|
|
558
490
|
const difference = arrays[0].filter(value => !set.has(value));
|
|
559
491
|
if (arrays.length > 2)
|
|
@@ -583,27 +515,30 @@ class Util {
|
|
|
583
515
|
Warning: Duplicate values are not handled consistently. Duplicates included only in one of the
|
|
584
516
|
arrays are retained, but if included in both only duplicates of A are retained. */
|
|
585
517
|
|
|
586
|
-
static arrayCompare(a, b) {
|
|
518
|
+
static arrayCompare(a: unknown[], b: unknown[]) {
|
|
587
519
|
const onlyA = [];
|
|
588
520
|
const onlyB = [];
|
|
589
521
|
const both = [];
|
|
590
522
|
const aSet = new Set(a);
|
|
591
523
|
const bSet = new Set(b);
|
|
524
|
+
|
|
592
525
|
for (const aValue of a)
|
|
593
526
|
if (bSet.has(aValue))
|
|
594
527
|
both.push(aValue);
|
|
595
528
|
else
|
|
596
529
|
onlyA.push(aValue);
|
|
530
|
+
|
|
597
531
|
for (const bValue of b)
|
|
598
532
|
if (!aSet.has(bValue))
|
|
599
533
|
onlyB.push(bValue);
|
|
534
|
+
|
|
600
535
|
return [onlyA, both, onlyB];
|
|
601
536
|
}
|
|
602
537
|
|
|
603
538
|
|
|
604
539
|
/* Split array into chunks of the given size. Last chunk may be shorter. */
|
|
605
540
|
|
|
606
|
-
static arrayChunks(a, chunkSize) {
|
|
541
|
+
static arrayChunks(a: unknown[], chunkSize: number) {
|
|
607
542
|
const result = [];
|
|
608
543
|
for (let i = 0; i < a.length; i += chunkSize)
|
|
609
544
|
result.push(a.slice(i, i + chunkSize));
|
|
@@ -617,7 +552,7 @@ class Util {
|
|
|
617
552
|
As an example, if an array of length 9 is split to chunks of maximum length 4,
|
|
618
553
|
three arrays of length 3 are returned. */
|
|
619
554
|
|
|
620
|
-
static arrayChunksEqual(a, maxChunkSize) {
|
|
555
|
+
static arrayChunksEqual(a: unknown[], maxChunkSize: number) {
|
|
621
556
|
const noChunks = Math.ceil(a.length / maxChunkSize);
|
|
622
557
|
const chunkSize = Math.ceil(a.length / noChunks);
|
|
623
558
|
return Util.arrayChunks(a, chunkSize);
|
|
@@ -630,7 +565,7 @@ class Util {
|
|
|
630
565
|
|
|
631
566
|
Currently only slope is used so the rest have been commented. */
|
|
632
567
|
|
|
633
|
-
static linearRegression(y, x) {
|
|
568
|
+
static linearRegression(y: number[], x: number[]) {
|
|
634
569
|
const n = y.length;
|
|
635
570
|
let sumX = 0;
|
|
636
571
|
let sumY = 0;
|
|
@@ -658,20 +593,29 @@ class Util {
|
|
|
658
593
|
}
|
|
659
594
|
|
|
660
595
|
|
|
661
|
-
|
|
596
|
+
/* Convert "camelCase" to "UPPER_CASE" */
|
|
597
|
+
|
|
598
|
+
static camelToUpperCase(s: string) {
|
|
662
599
|
return s.replaceAll(/[A-Z]/g, (match, offset) => (offset > 0 ? '_' : '') + match).toUpperCase();
|
|
663
600
|
}
|
|
664
601
|
|
|
665
|
-
|
|
602
|
+
/* Convert "camelCase" to "lower_case" */
|
|
603
|
+
|
|
604
|
+
static camelToLowerCase(s: string) {
|
|
666
605
|
return s.replaceAll(/[A-Z]/g, (match, offset) => (offset > 0 ? '_' : '') + match).toLowerCase();
|
|
667
606
|
}
|
|
668
607
|
|
|
669
608
|
|
|
670
|
-
static #tableColumns;
|
|
671
|
-
static #tableLogger;
|
|
672
|
-
static #tableRule;
|
|
609
|
+
static #tableColumns: { width: number, right?: boolean }[];
|
|
610
|
+
static #tableLogger: (message: string) => void;
|
|
611
|
+
static #tableRule: string;
|
|
612
|
+
|
|
613
|
+
/* Start printing table to console or given logger */
|
|
673
614
|
|
|
674
|
-
static tableStart(
|
|
615
|
+
static tableStart(
|
|
616
|
+
columns: { name: string, width: number, right?: boolean }[],
|
|
617
|
+
{ logger }: { logger?: (message: string) => void } = {}
|
|
618
|
+
) {
|
|
675
619
|
Util.#tableColumns = columns.map(({ name, width, right }) => ({
|
|
676
620
|
width: width || name.length,
|
|
677
621
|
right
|
|
@@ -683,7 +627,9 @@ class Util {
|
|
|
683
627
|
Util.#tableLogger(Util.#tableRule);
|
|
684
628
|
}
|
|
685
629
|
|
|
686
|
-
|
|
630
|
+
/* Print a table row */
|
|
631
|
+
|
|
632
|
+
static tableRow(...values: unknown[]) {
|
|
687
633
|
Util.#tableLogger(values.map((value, i) =>
|
|
688
634
|
Util.#tableColumns[i].right ?
|
|
689
635
|
String(value).padEnd(Util.#tableColumns[i].width) :
|
|
@@ -691,6 +637,8 @@ class Util {
|
|
|
691
637
|
).join(' '));
|
|
692
638
|
}
|
|
693
639
|
|
|
640
|
+
/* Print a horizontal line to end the table */
|
|
641
|
+
|
|
694
642
|
static tableEnd() {
|
|
695
643
|
Util.#tableLogger(Util.#tableRule);
|
|
696
644
|
}
|
|
@@ -698,26 +646,26 @@ class Util {
|
|
|
698
646
|
|
|
699
647
|
/* Asynchronous intervals, adapted from: https://dev.to/jsmccrumb/asynchronous-setinterval-4j69 */
|
|
700
648
|
|
|
701
|
-
static #asyncIntervals = [];
|
|
649
|
+
static #asyncIntervals: boolean[] = [];
|
|
702
650
|
|
|
703
|
-
static async #runAsyncInterval(callback
|
|
651
|
+
static async #runAsyncInterval(callback: () => Promise<void>, interval: number, intervalIndex: number) {
|
|
704
652
|
await callback();
|
|
705
653
|
if (Util.#asyncIntervals[intervalIndex])
|
|
706
|
-
setTimeout(() => Util.#runAsyncInterval(callback, interval, intervalIndex), interval);
|
|
654
|
+
setTimeout(() => void Util.#runAsyncInterval(callback, interval, intervalIndex), interval);
|
|
707
655
|
}
|
|
708
656
|
|
|
709
|
-
static setAsyncInterval(callback
|
|
657
|
+
static setAsyncInterval(callback: () => Promise<void>, interval: number) {
|
|
710
658
|
if (typeof callback === 'function') {
|
|
711
659
|
const intervalIndex = Util.#asyncIntervals.length;
|
|
712
660
|
Util.#asyncIntervals.push(true);
|
|
713
|
-
Util.#runAsyncInterval(callback, interval, intervalIndex);
|
|
661
|
+
void Util.#runAsyncInterval(callback, interval, intervalIndex);
|
|
714
662
|
return intervalIndex;
|
|
715
663
|
} else {
|
|
716
664
|
throw new Error('Callback must be a function');
|
|
717
665
|
}
|
|
718
666
|
}
|
|
719
667
|
|
|
720
|
-
static clearAsyncInterval(intervalIndex) {
|
|
668
|
+
static clearAsyncInterval(intervalIndex: number) {
|
|
721
669
|
if (Util.#asyncIntervals[intervalIndex])
|
|
722
670
|
Util.#asyncIntervals[intervalIndex] = false;
|
|
723
671
|
}
|
|
@@ -3,49 +3,57 @@ import path from 'path';
|
|
|
3
3
|
import zlib from 'zlib';
|
|
4
4
|
import dotenv from 'dotenv';
|
|
5
5
|
import findConfig from 'find-config';
|
|
6
|
-
import Util from './Util.
|
|
6
|
+
import Util from './Util.ts';
|
|
7
7
|
|
|
8
8
|
|
|
9
9
|
/* Additional utility functions that only work in Node.js */
|
|
10
10
|
|
|
11
11
|
class UtilNode extends Util {
|
|
12
12
|
|
|
13
|
-
|
|
13
|
+
static #envFileLoaded: Record<string,boolean> = {};
|
|
14
|
+
|
|
15
|
+
/* Return environment variable value. The given .env file is loaded with find-config
|
|
14
16
|
so that it is also loaded from a parent directory.
|
|
15
17
|
|
|
16
18
|
If the environment variable cannot be found the process exits with exit value 1. */
|
|
17
19
|
|
|
18
|
-
static
|
|
20
|
+
static env(name: string, envFile = '.env') {
|
|
19
21
|
|
|
20
|
-
static env(name, envFile = '.env') {
|
|
21
22
|
if (envFile in UtilNode.#envFileLoaded === false) {
|
|
23
|
+
const path = findConfig(envFile);
|
|
24
|
+
if (!path) {
|
|
25
|
+
console.warn(`Environment variable file "${envFile}" not found`);
|
|
26
|
+
process.exit(1);
|
|
27
|
+
}
|
|
28
|
+
|
|
22
29
|
dotenv.config({
|
|
23
|
-
path
|
|
30
|
+
path,
|
|
24
31
|
quiet: true
|
|
25
32
|
});
|
|
26
33
|
UtilNode.#envFileLoaded[envFile] = true;
|
|
27
34
|
}
|
|
28
35
|
|
|
29
36
|
const value = process.env[name];
|
|
30
|
-
if (value)
|
|
31
|
-
return value;
|
|
32
|
-
else {
|
|
37
|
+
if (!value) {
|
|
33
38
|
console.warn(`Environment variable ${name} not defined`);
|
|
34
39
|
process.exit(1);
|
|
35
40
|
}
|
|
41
|
+
|
|
42
|
+
return value;
|
|
36
43
|
}
|
|
37
44
|
|
|
38
45
|
|
|
39
|
-
/* Return a list of
|
|
40
|
-
|
|
46
|
+
/* Return a list of filenames under the given directory, recursively including
|
|
47
|
+
subdirectories. Optionally, the array to which the filenames are added can be
|
|
48
|
+
given as the second argument. */
|
|
41
49
|
|
|
42
|
-
static walkSync(dir,
|
|
50
|
+
static walkSync(dir: string, target: string[] = []) {
|
|
43
51
|
for (const file of fs.readdirSync(dir)) {
|
|
44
|
-
|
|
45
|
-
UtilNode.walkSync(path.join(dir, file),
|
|
46
|
-
|
|
52
|
+
target = fs.statSync(path.join(dir, file)).isDirectory() ?
|
|
53
|
+
UtilNode.walkSync(path.join(dir, file), target) :
|
|
54
|
+
target.concat(path.join(dir, file));
|
|
47
55
|
}
|
|
48
|
-
return
|
|
56
|
+
return target;
|
|
49
57
|
}
|
|
50
58
|
|
|
51
59
|
|
|
@@ -54,23 +62,23 @@ class UtilNode extends Util {
|
|
|
54
62
|
If the filename ends with ".gz" or ".br", it is decompressed first. If the filename
|
|
55
63
|
contains ".jsonc", then comments are removed before the JSON is parsed. */
|
|
56
64
|
|
|
57
|
-
static jsonRead(filename) {
|
|
58
|
-
let input = fs.readFileSync(filename);
|
|
65
|
+
static jsonRead(filename: string) {
|
|
66
|
+
let input = fs.readFileSync(filename).toString();
|
|
59
67
|
if (filename.endsWith('.gz'))
|
|
60
|
-
input = zlib.gunzipSync(input);
|
|
68
|
+
input = zlib.gunzipSync(input).toString();
|
|
61
69
|
if (filename.endsWith('.br'))
|
|
62
|
-
input = zlib.brotliDecompressSync(input);
|
|
70
|
+
input = zlib.brotliDecompressSync(input).toString();
|
|
63
71
|
if (filename.includes('.jsonc'))
|
|
64
72
|
input = input.toString().replaceAll(/\/\*.*?\*\//gs, '').replaceAll(/\/\/.*$/gm, '');
|
|
65
|
-
return JSON.parse(input);
|
|
73
|
+
return JSON.parse(input) as unknown;
|
|
66
74
|
}
|
|
67
75
|
|
|
68
76
|
|
|
69
77
|
/* Write object to file as JSON. If the filename ends with ".gz" or ".br", then the
|
|
70
78
|
file content is compressed before being written. */
|
|
71
79
|
|
|
72
|
-
static jsonWrite(filename, object, replacer = null, space = 2) {
|
|
73
|
-
let output = JSON.stringify(object, replacer, space);
|
|
80
|
+
static jsonWrite(filename: string, object: unknown, replacer = null, space = 2) {
|
|
81
|
+
let output: string | Buffer = JSON.stringify(object, replacer, space);
|
|
74
82
|
if (filename.endsWith('.gz'))
|
|
75
83
|
output = zlib.gzipSync(output);
|
|
76
84
|
if (filename.endsWith('.br'))
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@antti5/ship-tool-common",
|
|
3
|
-
"version": "1.1.
|
|
3
|
+
"version": "1.1.1",
|
|
4
4
|
"description": "Ship Tool common utils and library code",
|
|
5
5
|
"repository": {
|
|
6
6
|
"type": "git",
|
|
@@ -16,17 +16,19 @@
|
|
|
16
16
|
"tag": "bin/tag"
|
|
17
17
|
},
|
|
18
18
|
"exports": {
|
|
19
|
-
"./Util": "./lib/Util.
|
|
19
|
+
"./Util": "./lib/Util.ts",
|
|
20
20
|
"./Semaphore": "./lib/Semaphore.ts",
|
|
21
21
|
"./UID": "./lib/UID.ts",
|
|
22
22
|
"./Trajectory": "./lib/trajectory/Trajectory.ts",
|
|
23
|
-
"./node/Util": "./lib/UtilNode.
|
|
23
|
+
"./node/Util": "./lib/UtilNode.ts"
|
|
24
24
|
},
|
|
25
25
|
"scripts": {
|
|
26
26
|
"eslint": "eslint . --ignore-pattern \"node_modules/*\""
|
|
27
27
|
},
|
|
28
28
|
"devDependencies": {
|
|
29
29
|
"@eslint/js": "9.39.2",
|
|
30
|
+
"@types/find-config": "1.0.4",
|
|
31
|
+
"@types/node": "26.6.6",
|
|
30
32
|
"eslint": "9.36.0",
|
|
31
33
|
"globals": "16.4.0",
|
|
32
34
|
"typescript-eslint": "8.73.0"
|
package/tsconfig.json
CHANGED
|
@@ -1,24 +1,13 @@
|
|
|
1
1
|
{
|
|
2
2
|
"compilerOptions": {
|
|
3
|
-
// "tsBuildInfoFile": "./node_modules/.tmp/tsconfig.app.tsbuildinfo",
|
|
4
3
|
"target": "es2022",
|
|
5
|
-
// "useDefineForClassFields": true,
|
|
6
|
-
// "lib": [
|
|
7
|
-
// "es2022",
|
|
8
|
-
// "DOM",
|
|
9
|
-
// "DOM.Iterable"
|
|
10
|
-
// ],
|
|
11
4
|
"module": "nodenext",
|
|
12
|
-
|
|
13
|
-
// "skipLibCheck": true,
|
|
5
|
+
"types": ["node"],
|
|
14
6
|
|
|
15
7
|
/* Bundler mode */
|
|
16
8
|
"moduleResolution": "nodenext",
|
|
17
9
|
"allowImportingTsExtensions": true,
|
|
18
|
-
// "verbatimModuleSyntax": true,
|
|
19
|
-
// "moduleDetection": "force",
|
|
20
10
|
"noEmit": true,
|
|
21
|
-
// "jsx": "react-jsx",
|
|
22
11
|
|
|
23
12
|
/* Linting */
|
|
24
13
|
"strict": true,
|