-
-
Notifications
You must be signed in to change notification settings - Fork 83
Expand file tree
/
Copy pathUtils.ts
More file actions
407 lines (337 loc) · 8.97 KB
/
Utils.ts
File metadata and controls
407 lines (337 loc) · 8.97 KB
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
import Moment from 'moment/moment';
/**
* Clamp
*
* @param num
* @param min
* @param max
*/
export function clamp(num: number, min: number, max: number): number {
return Math.min(Math.max(num, min), max);
}
/**
* Clamp
*
* @param num
* @param min
* @param max
*/
export function optClamp(num: number | undefined, min: number, max: number): number | undefined {
return num !== undefined ? Math.min(Math.max(num, min), max) : undefined;
}
export function remapRange(
old_value: number,
old_min: number,
old_max: number,
new_min: number,
new_max: number,
): number {
return ((old_value - old_min) / (old_max - old_min)) * (new_max - new_min) + new_min;
}
/**
* js can't even implement modulo correctly...
*
* @param n
* @param m
*/
export function mod(n: number, m: number): number {
return ((n % m) + m) % m;
}
/**
* Checks if 2 arrays contain equal values, the arrays should have the same datatype. Order of the elements matters.
*
* @param arr1
* @param arr2
*/
export function areArraysEqual<T>(arr1: T[] | undefined, arr2: T[] | undefined): boolean {
if (arr1 == null && arr2 == null) {
return true;
}
if (arr1 == null || arr2 == null) {
return false;
}
if (arr1.length !== arr2.length) {
return false;
}
for (let i = 0; i < arr1.length; i++) {
if (arr1[i] !== arr2[i]) {
return false;
}
}
return true;
}
export function areObjectsEqual(obj1: unknown, obj2: unknown): boolean {
if (obj1 === null && obj2 === null) {
return true;
}
if (obj1 === null || obj2 === null) {
return false;
}
if (typeof obj1 !== typeof obj2) {
return false;
}
if (typeof obj1 === 'object' && typeof obj2 === 'object') {
// both are arrays
if (Array.isArray(obj1) && Array.isArray(obj2)) {
if (obj1.length !== obj2.length) {
return false;
}
for (let i = 0; i < obj1.length; i++) {
if (!areObjectsEqual(obj1[i], obj2[i])) {
return false;
}
}
return true;
}
// one is array and the other is not
if (Array.isArray(obj1) || Array.isArray(obj2)) {
return false;
}
const keys1 = Object.keys(obj1);
const keys2 = Object.keys(obj2);
if (keys1.length !== keys2.length) {
return false;
}
for (const key of keys1) {
// @ts-ignore
if (!areObjectsEqual(obj1[key], obj2[key])) {
return false;
}
}
return true;
}
return obj1 === obj2;
}
/**
* Checks if arr starts with base.
*
* @param arr
* @param base
*/
export function arrayStartsWith<T>(arr: T[], base: T[]): boolean {
for (let i = 0; i < base.length; i++) {
if (arr[i] !== base[i]) {
return false;
}
}
return true;
}
export function isTruthy(value: unknown): boolean {
return !!value;
}
export function isFalsy(value: unknown): boolean {
return !value;
}
export function deepFreeze<T extends object>(object: T): Readonly<T>;
export function deepFreeze<T extends object>(object: T | undefined): Readonly<T | undefined>;
export function deepFreeze<T extends object>(object: T | undefined): Readonly<T | undefined> {
if (object === undefined) {
return object;
}
// Retrieve the property names defined on object
const propNames: (string | symbol)[] = Reflect.ownKeys(object);
// Freeze properties before freezing self
for (const name of propNames) {
// @ts-ignore
const value: unknown = object[name];
if ((value && typeof value === 'object') || typeof value === 'function') {
deepFreeze(value);
}
}
return Object.freeze(object);
}
export function getUUID(): string {
return window.crypto.randomUUID();
}
export function isUrl(str: string): boolean {
try {
new URL(str);
return true;
} catch (_) {
return false;
}
}
export function tryParseUrl(str: string): URL | undefined {
try {
return new URL(str);
} catch (_) {
return undefined;
}
}
// inspired by https://stackoverflow.com/a/48764436
export class DecimalPrecision {
static round(value: number, decimalPlaces: number = 0): number {
const p = Math.pow(10, decimalPlaces || 0);
const n = value * p * (1 + Number.EPSILON);
return Math.round(n) / p;
}
static ceil(value: number, decimalPlaces: number = 0): number {
const p = Math.pow(10, decimalPlaces || 0);
const n = value * p * (1 - Math.sign(value) * Number.EPSILON);
return Math.ceil(n) / p;
}
static floor(value: number, decimalPlaces: number = 0): number {
const p = Math.pow(10, decimalPlaces || 0);
const n = value * p * (1 + Math.sign(value) * Number.EPSILON);
return Math.floor(n) / p;
}
static trunc(value: number, decimalPlaces: number = 0): number {
return value < 0 ? DecimalPrecision.ceil(value, decimalPlaces) : DecimalPrecision.floor(value, decimalPlaces);
}
static toFixed(value: number, decimalPlaces: number = 0): string {
return DecimalPrecision.round(value, decimalPlaces).toFixed(decimalPlaces || 0);
}
}
export function openURL(link: string): void {
window.open(link, '_blank');
}
export type Tuple<T> = [T, ...T[]];
export function toEnumeration(
arr: string[],
map: (x: string) => string,
separator: string = ', ',
lastSeparator: string = 'and',
): string {
if (arr.length === 0) {
return '';
}
arr = arr.map(map);
if (arr.length === 1) {
return arr[0];
}
if (arr.length === 2) {
return `${arr[0]} ${lastSeparator} ${arr[1]}`;
}
return `${arr.slice(0, -1).join(separator)} ${lastSeparator} ${arr.slice(-1)}`;
}
export function expectType<T>(_: T): void {
// no op
}
export function showUnloadedMessage(container: HTMLElement, subject: string): void {
container.innerHTML = '';
container.className = '';
const span = document.createElement('span');
span.className = 'mb-warning mb-unloaded';
span.innerText = `[MB_UNLOADED] ${subject}`;
container.appendChild(span);
}
export class DomHelpers {
static createElement<K extends keyof HTMLElementTagNameMap>(
parent: HTMLElement,
tagName: K,
options?: {
text?: string;
class?: string;
},
): HTMLElementTagNameMap[K] {
const el = document.createElement(tagName);
if (options?.text) {
el.innerText = options.text;
}
if (options?.class) {
el.className = options.class;
}
parent.appendChild(el);
return el;
}
static addClass(el: HTMLElement, cls: string): void {
el.classList.add(...cls.split(' '));
}
static addClasses(el: HTMLElement, cls: string[]): void {
el.classList.add(...cls);
}
static removeClass(el: HTMLElement, cls: string): void {
el.classList.remove(...cls.split(' '));
}
static hasClass(el: HTMLElement, cls: string): boolean {
return el.classList.contains(cls);
}
static removeAllClasses(el: HTMLElement): void {
el.className = '';
}
static empty(el: HTMLElement): void {
while (el.lastChild) {
el.removeChild(el.lastChild);
}
}
}
export function getFolderPathFromFilePath(filePath: string): string {
const pathSeparator = filePath.lastIndexOf('/');
if (pathSeparator === -1) {
return '';
}
return filePath.substring(0, pathSeparator);
}
/**
* Joins the given paths together without duplicate slashes.
*/
export function joinPath(...paths: string[]): string {
if (paths.length === 0) {
return '/';
}
if (paths.length === 1) {
return cleanPath(paths[0]);
}
let result = paths[0].startsWith('/') ? paths[0].substring(1) : paths[0];
for (let i = 1; i < paths.length; i++) {
if (paths[i] === '' || paths[i] === '/') {
continue;
}
const endsWithSlash = result.endsWith('/');
const startsWithSlash = paths[i].startsWith('/');
if (endsWithSlash && startsWithSlash) {
result += paths[i].substring(1);
} else if (!endsWithSlash && !startsWithSlash) {
result += '/' + paths[i];
} else {
result += paths[i];
}
}
return cleanPath(result);
}
export function cleanPath(path: string): string {
if (path.startsWith('/')) {
path = path.substring(1);
}
if (path.endsWith('/')) {
path = path.substring(0, path.length - 1);
}
return path === '' ? '/' : path;
}
/**
* Ensures that the file path has the given extension.
*/
export function ensureFileExtension(filePath: string, extension: string): string {
extension = extension.startsWith('.') ? extension : '.' + extension;
if (filePath.endsWith(extension)) {
return filePath;
}
return filePath + extension;
}
/**
* Processes date format placeholders in a string.
* Replaces patterns like {YYYY-MM-DD} with formatted dates using moment.js.
*/
export function processDateFormatPlaceholders(value: string | undefined): string | undefined {
if (value === undefined || value === '') {
return value;
}
const placeholderRegex = /\{([^}]+)\}/g;
return value.replace(placeholderRegex, (match, format: string) => {
// Validate that the format string only contains valid moment.js tokens and delimiters
// Moment.js tokens: Y M D d H h m s S a A Q W w X x Z z G g E e o k l
// Common delimiters: : / - space . , [ ]
const validMomentFormat = /^[YMDdHhmsaAQWwXxZzGgEeSsokl:/\-\s.,[\]]+$/.test(format);
if (!validMomentFormat) {
// Leave unknown/invalid formats unchanged
return match;
}
return Moment().format(format);
});
}
export function toArray<T>(value: T | T[] | undefined): T[] {
if (value === undefined) {
return [];
}
return Array.isArray(value) ? value : [value];
}