@develia/commons 0.3.17 → 0.3.20

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.
@@ -0,0 +1,1339 @@
1
+ (function (exports) {
2
+ 'use strict';
3
+
4
+ /**
5
+ * Represents different types in JavaScript.
6
+ * @enum {string}
7
+ */
8
+ exports.Type = void 0;
9
+ (function (Type) {
10
+ Type["Undefined"] = "undefined";
11
+ Type["Number"] = "number";
12
+ Type["String"] = "string";
13
+ Type["Boolean"] = "boolean";
14
+ Type["Object"] = "object";
15
+ Type["Function"] = "function";
16
+ Type["Symbol"] = "symbol";
17
+ Type["BigInt"] = "bigint";
18
+ Type["Null"] = "null";
19
+ })(exports.Type || (exports.Type = {}));
20
+
21
+ /**
22
+ * Represents a pair of key and value.
23
+ *
24
+ * @template TKey The type of the key.
25
+ * @template TValue The type of the value.
26
+ */
27
+ class Pair {
28
+ get value() {
29
+ return this._value;
30
+ }
31
+ get key() {
32
+ return this._key;
33
+ }
34
+ constructor(key, value) {
35
+ this._key = key;
36
+ this._value = value;
37
+ }
38
+ }
39
+
40
+ // noinspection JSUnusedGlobalSymbols
41
+ /**
42
+ * Checks if an object is iterable.
43
+ *
44
+ * @param {any} obj - The object to check.
45
+ * @return {boolean} - Returns true if the object is iterable, otherwise false.
46
+ */
47
+ function isIterable(obj) {
48
+ return obj[Symbol.iterator] === 'function';
49
+ }
50
+ /**
51
+ * Checks if a given value is a string.
52
+ *
53
+ * @param {*} value - The value to check.
54
+ * @return {boolean} - Returns true if the value is a string, otherwise returns false.
55
+ */
56
+ function isString(value) {
57
+ return typeof value === 'string';
58
+ }
59
+ /**
60
+ * Checks if a value is a number.
61
+ *
62
+ * @param {any} value - The value to check.
63
+ * @return {boolean} - Returns true if the value is a number, otherwise false.
64
+ */
65
+ function isNumber(value) {
66
+ return typeof value === 'number';
67
+ }
68
+ /**
69
+ * Checks if a given value is a boolean.
70
+ *
71
+ * @param {any} value - The value to be checked.
72
+ *
73
+ * @return {boolean} - Returns true if the value is a boolean, otherwise false.
74
+ */
75
+ function isBoolean(value) {
76
+ return typeof value === 'boolean';
77
+ }
78
+ /**
79
+ * Checks if a value is an object.
80
+ * @param {any} value - The value to be checked.
81
+ * @returns {boolean} - Returns true if the value is an object, otherwise returns false.
82
+ */
83
+ function isObject(value) {
84
+ return value != null && typeof value === 'object' && !Array.isArray(value);
85
+ }
86
+ /**
87
+ * Determines if a value is an array.
88
+ *
89
+ * @param value - The value to be checked.
90
+ *
91
+ * @return Whether the value is an array.
92
+ */
93
+ function isArray(value) {
94
+ return Array.isArray(value);
95
+ }
96
+ /**
97
+ * Checks if a value is a function.
98
+ *
99
+ * @param {any} value - The value to be checked.
100
+ * @return {boolean} - Returns true if the value is a function, otherwise returns false.
101
+ */
102
+ function isFunction(value) {
103
+ return typeof value === 'function';
104
+ }
105
+ /**
106
+ * Checks if a value is undefined.
107
+ *
108
+ * @param {any} value - The value to check.
109
+ * @returns {boolean} - True if the value is undefined, false otherwise.
110
+ */
111
+ function isUndefined(value) {
112
+ return typeof value === 'undefined';
113
+ }
114
+ /**
115
+ * Checks if a value is defined or not.
116
+ *
117
+ * @param {any} value - The value to be checked.
118
+ *
119
+ * @return {boolean} - True if the value is defined, false otherwise.
120
+ */
121
+ function isDefined(value) {
122
+ return typeof value !== 'undefined';
123
+ }
124
+ /**
125
+ * Checks if a given value is null.
126
+ *
127
+ * @param {any} value - The value to check for null.
128
+ * @return {boolean} - Returns true if the value is null, otherwise returns false.
129
+ */
130
+ function isNull(value) {
131
+ return value === null;
132
+ }
133
+ /**
134
+ * Determines whether the given value is of type bigint.
135
+ * @param {any} value - The value to be checked.
136
+ * @return {boolean} - Returns true if the value is of type bigint, false otherwise.
137
+ */
138
+ function isBigInt(value) {
139
+ return typeof value === 'bigint';
140
+ }
141
+ /**
142
+ * Checks if a given value is a symbol.
143
+ *
144
+ * @param {any} value - The value to be checked.
145
+ * @return {boolean} - Returns true if the value is a symbol, false otherwise.
146
+ */
147
+ function isSymbol(value) {
148
+ return typeof value === 'symbol';
149
+ }
150
+ /**
151
+ * Checks if a value is null or undefined.
152
+ *
153
+ * @param {any} value - The value to check.
154
+ * @return {boolean} - Returns true if the value is null or undefined, false otherwise.
155
+ */
156
+ function isNullOrUndefined(value) {
157
+ return value === null || typeof value === 'undefined';
158
+ }
159
+ /**
160
+ * Checks if a given value is empty.
161
+ *
162
+ * @param {any} value - The value to check.
163
+ * @return {boolean} - Returns true if the value is empty, otherwise returns false.
164
+ */
165
+ function isEmpty(value) {
166
+ return (Array.isArray(value) && value.length === 0) ||
167
+ (typeof value === 'string' && value === '') ||
168
+ value === null || typeof value === 'undefined';
169
+ }
170
+ /**
171
+ * Check if a value is empty or contains only whitespace characters.
172
+ *
173
+ * @param {any} value - The value to check.
174
+ * @return {boolean} Returns true if the value is empty or contains only whitespace characters, otherwise returns false.
175
+ */
176
+ function isEmptyOrWhitespace(value) {
177
+ return (Array.isArray(value) && value.length === 0) ||
178
+ (typeof value === 'string' && value.trim() === '') ||
179
+ value === null || typeof value === 'undefined';
180
+ }
181
+ /**
182
+ * Submits a form via AJAX and returns a Promise that resolves to the Response object.
183
+ *
184
+ * @param {HTMLFormElement | string} selectorOrElement - The form element or selector.
185
+ * @return {Promise<Response>} A Promise that resolves to the Response object.
186
+ * @throws {Error} If the element is invalid.
187
+ */
188
+ async function ajaxSubmit(selectorOrElement) {
189
+ const form = typeof selectorOrElement === 'string'
190
+ ? document.querySelector(selectorOrElement)
191
+ : selectorOrElement;
192
+ if (!(form instanceof HTMLFormElement)) {
193
+ throw new Error("Invalid element.");
194
+ }
195
+ // Crear un objeto FormData a partir del formulario
196
+ return await fetch(form.action, {
197
+ method: form.method,
198
+ body: new FormData(form),
199
+ });
200
+ }
201
+ /**
202
+ * Converts an object into an array of key-value pairs.
203
+ *
204
+ * @param {Record<string, any>} obj - The object to convert.
205
+ * @return {Pair<string, any>[]} - The array of key-value pairs.
206
+ */
207
+ function toPairs(obj) {
208
+ let output = [];
209
+ for (const key in obj) {
210
+ output.push(new Pair(key, obj[key]));
211
+ }
212
+ return output;
213
+ }
214
+ /**
215
+ * Converts a given thing into a Promise.
216
+ * @template T
217
+ * @param {any} thing - The thing to be converted into a Promise.
218
+ * @returns {Promise<T>} - A Promise representing the given thing.
219
+ */
220
+ function promisify(thing) {
221
+ if (thing instanceof Promise)
222
+ return thing;
223
+ if (isFunction(thing)) {
224
+ return new Promise((resolve, reject) => {
225
+ try {
226
+ const result = thing();
227
+ resolve(result);
228
+ }
229
+ catch (error) {
230
+ reject(error);
231
+ }
232
+ });
233
+ }
234
+ return Promise.resolve(thing);
235
+ }
236
+ function ajaxSubmission(selectorOrElement, onSuccess = undefined, onFailure = undefined) {
237
+ const form = typeof selectorOrElement === 'string'
238
+ ? document.querySelector(selectorOrElement)
239
+ : selectorOrElement;
240
+ if (!(form instanceof HTMLFormElement)) {
241
+ return;
242
+ }
243
+ form.addEventListener('submit', async (event) => {
244
+ event.preventDefault();
245
+ let promise = ajaxSubmit(form);
246
+ if (promise) {
247
+ if (onSuccess)
248
+ promise = promise.then(onSuccess);
249
+ if (onFailure)
250
+ promise.catch(onFailure);
251
+ }
252
+ });
253
+ }
254
+ /**
255
+ * Creates a deep clone of the given object.
256
+ * @template T
257
+ * @param {T} obj - The object to clone.
258
+ * @return {T} - The deep clone of the given object.
259
+ */
260
+ function deepClone(obj) {
261
+ if (obj === null || typeof obj !== 'object') {
262
+ return obj;
263
+ }
264
+ if (Array.isArray(obj)) {
265
+ const copy = [];
266
+ for (const element of obj) {
267
+ copy.push(deepClone(element));
268
+ }
269
+ return copy;
270
+ }
271
+ const copy = {};
272
+ for (const key in obj) {
273
+ if (obj.hasOwnProperty(key)) {
274
+ copy[key] = deepClone(obj[key]);
275
+ }
276
+ }
277
+ return copy;
278
+ }
279
+ /**
280
+ * Returns the type of the given value.
281
+ *
282
+ * @param {any} value - The value to determine the type of.
283
+ * @return {Type} - The type of the given value.
284
+ */
285
+ function getType(value) {
286
+ return value === null ? exports.Type.Null : exports.Type[typeof value];
287
+ }
288
+ /**
289
+ * Converts an object to `FormData` format recursively.
290
+ *
291
+ * @param {Record<string, any>} data - The object data to convert.
292
+ * @param {FormData} formData - The `FormData` instance to append data to.
293
+ * @param {string} parentKey - The parent key to append to child keys in the `FormData`.
294
+ * @returns {FormData} - The `FormData` instance with the converted data.
295
+ */
296
+ function _objectToFormData(data, formData, parentKey = '') {
297
+ for (const key in data) {
298
+ if (data.hasOwnProperty(key)) {
299
+ const value = data[key];
300
+ if (value instanceof Date) {
301
+ formData.append(parentKey ? `${parentKey}[${key}]` : key, value.toISOString());
302
+ }
303
+ else if (value instanceof File) {
304
+ formData.append(parentKey ? `${parentKey}[${key}]` : key, value);
305
+ }
306
+ else if (typeof value === 'object' && !Array.isArray(value)) {
307
+ _objectToFormData(value, formData, parentKey ? `${parentKey}[${key}]` : key);
308
+ }
309
+ else if (Array.isArray(value)) {
310
+ value.forEach((item, index) => {
311
+ const arrayKey = `${parentKey ? `${parentKey}[${key}]` : key}[${index}]`;
312
+ if (typeof item === 'object' && !Array.isArray(item)) {
313
+ _objectToFormData(item, formData, arrayKey);
314
+ }
315
+ else {
316
+ formData.append(arrayKey, item);
317
+ }
318
+ });
319
+ }
320
+ else {
321
+ formData.append(parentKey ? `${parentKey}[${key}]` : key, value);
322
+ }
323
+ }
324
+ }
325
+ return formData;
326
+ }
327
+ /**
328
+ * Converts an object into FormData.
329
+ *
330
+ * @param {Record<string, any>} data - The object to be converted into FormData.
331
+ * @return {FormData} - The FormData object representing the converted data.
332
+ */
333
+ function objectToFormData(data) {
334
+ let formData = new FormData();
335
+ return _objectToFormData(data, formData);
336
+ }
337
+
338
+ /**
339
+ * Ensures that a given string has a specific prefix.
340
+ *
341
+ * @param {string} str - The string to ensure the prefix on.
342
+ * @param {string} prefix - The prefix to ensure on the string.
343
+ * @return {string} - The resulting string with the ensured prefix.
344
+ */
345
+ function ensurePrefix(str, prefix) {
346
+ if (!str.startsWith(prefix))
347
+ return prefix + str;
348
+ return str;
349
+ }
350
+ /**
351
+ * Ensures that a string ends with a specified suffix.
352
+ *
353
+ * @param {string} str - The original string.
354
+ * @param {string} suffix - The suffix to ensure.
355
+ * @return {string} - The modified string with the suffix added if it was not already present.
356
+ */
357
+ function ensureSuffix(str, suffix) {
358
+ if (!str.endsWith(suffix))
359
+ return str + suffix;
360
+ return str;
361
+ }
362
+ /**
363
+ * Formats a string using a template and provided arguments.
364
+ *
365
+ * @param {string} template - The template string containing placeholders.
366
+ * @param {any[]} args - Optional arguments to replace the placeholders in the template.
367
+ * @return {string} The formatted string.
368
+ */
369
+ function format(template, ...args) {
370
+ let regex;
371
+ if (args.length === 1 && typeof args[0] === 'object') {
372
+ args = args[0];
373
+ regex = /{(.+?)}/g;
374
+ }
375
+ else {
376
+ regex = /{(\d+?)}/g;
377
+ }
378
+ return template.replace(regex, (match, key) => {
379
+ return typeof args[key] !== 'undefined' ? args[key] : "";
380
+ });
381
+ }
382
+
383
+ /**
384
+ * Linearly interpolates a number between two ranges.
385
+ *
386
+ * @param {number} n - The number to interpolate.
387
+ * @param {number} inMin - The minimum value of the input range.
388
+ * @param {number} inMax - The maximum value of the input range.
389
+ * @param {number} outMin - The minimum value of the output range.
390
+ * @param {number} outMax - The maximum value of the output range.
391
+ *
392
+ * @return {number} - The interpolated value.
393
+ */
394
+ function lerp(n, inMin, inMax, outMin, outMax) {
395
+ return outMin + (outMax - outMin) * ((n - inMin) / (inMax - inMin));
396
+ }
397
+ /**
398
+ * Clamps a number between a minimum and maximum value.
399
+ *
400
+ * @param {number} n - The value to be clamped.
401
+ * @param {number} min - The minimum value.
402
+ * @param {number} max - The maximum value.
403
+ * @return {number} The clamped value.
404
+ */
405
+ function clamp(n, min, max) {
406
+ if (n <= min)
407
+ return min;
408
+ if (n >= max)
409
+ return max;
410
+ return n;
411
+ }
412
+
413
+ class CacheDictionary {
414
+ constructor(fallback = null, defaultDuration = null) {
415
+ this.fallback = fallback;
416
+ this.cache = {};
417
+ this.defaultDuration = defaultDuration;
418
+ this.expiration = {};
419
+ }
420
+ getExpiration(key) {
421
+ return this.expiration[key];
422
+ }
423
+ setExpiration(key, expiration) {
424
+ this.expiration[key] = expiration;
425
+ }
426
+ setDuration(key, duration) {
427
+ if (duration === null) {
428
+ delete this.expiration[key];
429
+ }
430
+ else {
431
+ const expiration = new Date();
432
+ expiration.setSeconds(expiration.getSeconds() + duration);
433
+ this.expiration[key] = expiration;
434
+ }
435
+ }
436
+ get(key) {
437
+ if (!this.cache.hasOwnProperty(key)) {
438
+ if (this.fallback) {
439
+ this.cache[key] = this.fallback(key);
440
+ this.expiration[key] = this.calculateExpiration(this.defaultDuration);
441
+ }
442
+ else {
443
+ return null;
444
+ }
445
+ }
446
+ if (this.isExpired(key)) {
447
+ this.remove(key);
448
+ return null;
449
+ }
450
+ return this.cache[key];
451
+ }
452
+ set(key, value, duration = null) {
453
+ this.cache[key] = value;
454
+ this.expiration[key] = this.calculateExpiration(duration);
455
+ }
456
+ remove(key) {
457
+ delete this.cache[key];
458
+ delete this.expiration[key];
459
+ }
460
+ isExpired(key) {
461
+ const expiration = this.expiration[key];
462
+ if (expiration instanceof Date) {
463
+ return expiration < new Date();
464
+ }
465
+ return false;
466
+ }
467
+ calculateExpiration(duration) {
468
+ if (duration === null) {
469
+ return undefined;
470
+ }
471
+ const expiration = new Date();
472
+ expiration.setSeconds(expiration.getSeconds() + duration);
473
+ return expiration;
474
+ }
475
+ }
476
+
477
+ function from(source) {
478
+ if (source == null)
479
+ throw "Source is null.";
480
+ if (typeof source === 'function')
481
+ return From.fn(source);
482
+ if (typeof source[Symbol.iterator] === 'function') {
483
+ return From.iterable(source);
484
+ }
485
+ else if (typeof source === 'object') {
486
+ return From.object(source);
487
+ }
488
+ throw "Invalid source.";
489
+ }
490
+ class From {
491
+ static object(obj) {
492
+ return new From(function () {
493
+ return toPairs(obj);
494
+ });
495
+ }
496
+ static _shallowEqual(obj1, obj2) {
497
+ const keys1 = Object.keys(obj1);
498
+ const keys2 = Object.keys(obj2);
499
+ if (keys1.length !== keys2.length) {
500
+ return false;
501
+ }
502
+ for (let key of keys1) {
503
+ if (obj1[key] !== obj2[key]) {
504
+ return false;
505
+ }
506
+ }
507
+ return true;
508
+ }
509
+ constructor(fn) {
510
+ this._fn = fn;
511
+ }
512
+ static fn(callable) {
513
+ return new From(callable);
514
+ }
515
+ ;
516
+ collect() {
517
+ const cache = Array.from(this);
518
+ return From.iterable(cache);
519
+ }
520
+ static iterable(iterable) {
521
+ return From.fn(function* () {
522
+ for (const item of iterable) {
523
+ yield item;
524
+ }
525
+ });
526
+ }
527
+ ;
528
+ map(mapper) {
529
+ const self = this;
530
+ return From.fn(function* () {
531
+ for (let item of self) {
532
+ yield mapper(item);
533
+ }
534
+ });
535
+ }
536
+ *[Symbol.iterator]() {
537
+ yield* this._fn();
538
+ }
539
+ all(predicate) {
540
+ for (let item of this._fn()) {
541
+ if (!predicate(item)) {
542
+ return false;
543
+ }
544
+ }
545
+ return true;
546
+ }
547
+ any(predicate) {
548
+ for (let item of this) {
549
+ if (predicate(item)) {
550
+ return true;
551
+ }
552
+ }
553
+ return false;
554
+ }
555
+ filter(predicate) {
556
+ const self = this;
557
+ return From.fn(function* () {
558
+ for (let item of self) {
559
+ if (predicate(item)) {
560
+ yield item;
561
+ }
562
+ }
563
+ });
564
+ }
565
+ contains(value) {
566
+ for (let item of this) {
567
+ if (item === value) {
568
+ return true;
569
+ }
570
+ }
571
+ return false;
572
+ }
573
+ // noinspection LoopStatementThatDoesntLoopJS
574
+ first(predicate) {
575
+ if (predicate) {
576
+ for (let item of this) {
577
+ if (!predicate || predicate(item)) {
578
+ return item;
579
+ }
580
+ }
581
+ }
582
+ else {
583
+ // noinspection LoopStatementThatDoesntLoopJS
584
+ for (let item of this) {
585
+ return item;
586
+ }
587
+ }
588
+ return undefined;
589
+ }
590
+ append(item) {
591
+ const self = this;
592
+ return From.fn(function* () {
593
+ for (let element of self) {
594
+ yield element;
595
+ }
596
+ yield item;
597
+ });
598
+ }
599
+ prepend(item) {
600
+ const self = this;
601
+ return From.fn(function* () {
602
+ yield item;
603
+ for (let element of self) {
604
+ yield element;
605
+ }
606
+ });
607
+ }
608
+ at(index) {
609
+ let idx = 0;
610
+ for (let item of this) {
611
+ if (idx++ === index) {
612
+ return item;
613
+ }
614
+ }
615
+ return undefined;
616
+ }
617
+ last(predicate) {
618
+ let last = undefined;
619
+ if (predicate)
620
+ for (let item of this) {
621
+ if (!predicate || predicate(item)) {
622
+ last = item;
623
+ }
624
+ }
625
+ else {
626
+ for (let item of this) {
627
+ last = item;
628
+ }
629
+ }
630
+ return last;
631
+ }
632
+ mapMany(mapper) {
633
+ const self = this;
634
+ return From.fn(function* () {
635
+ for (const item of self) {
636
+ const subitems = mapper(item);
637
+ for (const subitem of subitems) {
638
+ yield subitem;
639
+ }
640
+ }
641
+ });
642
+ }
643
+ flatten() {
644
+ const self = this;
645
+ return From.fn(function* () {
646
+ for (let item of self) {
647
+ let temp = item;
648
+ for (let subitem of temp) {
649
+ yield subitem;
650
+ }
651
+ }
652
+ });
653
+ }
654
+ sum(mapper) {
655
+ let total = 0;
656
+ if (mapper)
657
+ for (let item of this) {
658
+ total += mapper(item);
659
+ }
660
+ else
661
+ for (let item of this) {
662
+ total += item;
663
+ }
664
+ return total;
665
+ }
666
+ avg(mapper) {
667
+ let total = 0;
668
+ let count = 0;
669
+ if (mapper)
670
+ for (let item of this) {
671
+ total += mapper(item);
672
+ count++;
673
+ }
674
+ else
675
+ for (let item of this) {
676
+ total += item;
677
+ count++;
678
+ }
679
+ return count > 0 ? total / count : 0;
680
+ }
681
+ max(mapper) {
682
+ let max = -Infinity;
683
+ for (let item of this) {
684
+ let value = mapper(item);
685
+ max = value > max ? value : max;
686
+ }
687
+ return max;
688
+ }
689
+ min(mapper) {
690
+ let min = Infinity;
691
+ for (let item of this) {
692
+ let value = mapper(item);
693
+ min = value < min ? value : min;
694
+ }
695
+ return min;
696
+ }
697
+ maxBy(mapper) {
698
+ let max = -Infinity;
699
+ let maxItem;
700
+ for (let item of this) {
701
+ let value = mapper(item);
702
+ if (value > max) {
703
+ max = value;
704
+ maxItem = item;
705
+ }
706
+ }
707
+ return maxItem;
708
+ }
709
+ minBy(mapper) {
710
+ let min = Infinity;
711
+ let minItem;
712
+ for (let item of this) {
713
+ let value = mapper(item);
714
+ if (value < min) {
715
+ min = value;
716
+ minItem = item;
717
+ }
718
+ }
719
+ return minItem;
720
+ }
721
+ orderBy(mapper) {
722
+ const array = Array.from(this._fn());
723
+ array.sort((a, b) => {
724
+ const aValue = mapper(a);
725
+ const bValue = mapper(b);
726
+ return aValue > bValue ? 1 : aValue < bValue ? -1 : 0;
727
+ });
728
+ return From.iterable(array);
729
+ }
730
+ groupBy(keySelector, equalityComparer) {
731
+ equalityComparer = (equalityComparer == null ? From._shallowEqual : equalityComparer);
732
+ const self = this;
733
+ return From.fn(function* () {
734
+ const groups = [];
735
+ for (let item of self) {
736
+ const key = keySelector(item);
737
+ let found = false;
738
+ for (let [entryKey, group] of groups) {
739
+ if (equalityComparer(key, entryKey)) {
740
+ group.push(item);
741
+ found = true;
742
+ break;
743
+ }
744
+ }
745
+ if (!found) {
746
+ groups.push([key, [item]]);
747
+ }
748
+ }
749
+ yield* groups.map(([key, values]) => new Grouping(key, values));
750
+ });
751
+ }
752
+ head(n) {
753
+ const self = this;
754
+ return From.fn(function* () {
755
+ let count = 0;
756
+ for (let item of self) {
757
+ if (count++ < n) {
758
+ yield item;
759
+ }
760
+ else {
761
+ return;
762
+ }
763
+ }
764
+ });
765
+ }
766
+ tail(n) {
767
+ const self = this;
768
+ return From.fn(function* () {
769
+ let buffer = [];
770
+ for (let item of self) {
771
+ buffer.push(item);
772
+ if (buffer.length > n) {
773
+ buffer.shift();
774
+ }
775
+ }
776
+ yield* buffer;
777
+ });
778
+ }
779
+ forEach(action) {
780
+ for (let item of this) {
781
+ action(item);
782
+ }
783
+ }
784
+ toArray() {
785
+ return Array.from(this);
786
+ }
787
+ instancesOf(type) {
788
+ return this.filter(item => typeof item === type);
789
+ }
790
+ allInstanceOf(type) {
791
+ for (let item of this) {
792
+ if (!(item instanceof type)) {
793
+ return false;
794
+ }
795
+ }
796
+ return true;
797
+ }
798
+ distinct(eq_comparer) {
799
+ if (eq_comparer == null)
800
+ eq_comparer = From._shallowEqual;
801
+ const self = this;
802
+ return From.fn(function* () {
803
+ const included = [];
804
+ for (let item of self) {
805
+ if (!From.iterable(included).any(x => eq_comparer(x, item))) {
806
+ included.push(item);
807
+ yield item;
808
+ }
809
+ }
810
+ });
811
+ }
812
+ insert(item, index) {
813
+ const self = this;
814
+ return From.fn(function* () {
815
+ let i = 0;
816
+ let inserted = false;
817
+ for (let existingItem of self) {
818
+ if (i === index) {
819
+ yield item;
820
+ inserted = true;
821
+ }
822
+ yield existingItem;
823
+ i++;
824
+ }
825
+ if (!inserted) {
826
+ yield item;
827
+ }
828
+ });
829
+ }
830
+ skip(n) {
831
+ const self = this;
832
+ return From.fn(function* () {
833
+ let i = 0;
834
+ for (let item of self) {
835
+ if (i >= n) {
836
+ yield item;
837
+ }
838
+ i++;
839
+ }
840
+ });
841
+ }
842
+ union(other) {
843
+ const self = this;
844
+ return From.fn(function* () {
845
+ yield* self;
846
+ yield* other;
847
+ });
848
+ }
849
+ innerJoin(other, thisKeySelector, otherKeySelector, resultSelector) {
850
+ const self = this;
851
+ return From.fn(() => {
852
+ const otherByKey = new Map();
853
+ for (let item of other) {
854
+ otherByKey.set(otherKeySelector(item), item);
855
+ }
856
+ return Array.from(self)
857
+ .filter(item => otherByKey.has(thisKeySelector(item)))
858
+ .map(item => resultSelector(item, otherByKey.get(thisKeySelector(item))));
859
+ });
860
+ }
861
+ leftJoin(other, thisKeySelector, otherKeySelector, resultSelector) {
862
+ const self = this;
863
+ return From.fn(() => {
864
+ const otherByKey = new Map();
865
+ for (let item of other) {
866
+ otherByKey.set(otherKeySelector(item), item);
867
+ }
868
+ return Array.from(self).map(item => resultSelector(item, otherByKey.get(thisKeySelector(item))));
869
+ });
870
+ }
871
+ leftGroupJoin(other, thisKeySelector, otherKeySelector, resultSelector) {
872
+ const self = this;
873
+ return From.fn(() => {
874
+ const otherByKeys = new Map();
875
+ for (let item of other) {
876
+ const key = otherKeySelector(item);
877
+ if (!otherByKeys.has(key)) {
878
+ otherByKeys.set(key, []);
879
+ }
880
+ otherByKeys.get(key).push(item);
881
+ }
882
+ return Array.from(self).map(item => resultSelector(item, otherByKeys.get(thisKeySelector(item)) || []));
883
+ });
884
+ }
885
+ rightGroupJoin(other, thisKeySelector, otherKeySelector, resultSelector) {
886
+ const self = this;
887
+ return From.fn(() => {
888
+ const thisByKeys = new Map();
889
+ for (let item of self) {
890
+ const key = thisKeySelector(item);
891
+ if (!thisByKeys.has(key)) {
892
+ thisByKeys.set(key, []);
893
+ }
894
+ thisByKeys.get(key).push(item);
895
+ }
896
+ return Array.from(other).map(item => resultSelector(thisByKeys.get(otherKeySelector(item)) || [], item));
897
+ });
898
+ }
899
+ rightJoin(other, thisKeySelector, otherKeySelector, resultSelector) {
900
+ const self = this;
901
+ return From.fn(() => {
902
+ const thisByKey = new Map();
903
+ for (let item of self) {
904
+ thisByKey.set(thisKeySelector(item), item);
905
+ }
906
+ return Array.from(other).map(item => resultSelector(thisByKey.get(otherKeySelector(item)), item));
907
+ });
908
+ }
909
+ }
910
+ class Grouping extends From {
911
+ get key() {
912
+ return this._key;
913
+ }
914
+ constructor(key, values) {
915
+ super(() => values);
916
+ this._key = key;
917
+ }
918
+ }
919
+
920
+ /**
921
+ * A class representing a timer that executes a callback function at a specified interval.
922
+ */
923
+ class Timer {
924
+ /**
925
+ * @param callback Callback
926
+ * @param interval Seconds between calls
927
+ */
928
+ constructor(callback, interval) {
929
+ this._callback = callback;
930
+ this._interval = interval;
931
+ this._intervalId = null;
932
+ }
933
+ get running() {
934
+ return this._intervalId !== null && this._intervalId !== undefined;
935
+ }
936
+ get interval() {
937
+ return this._interval;
938
+ }
939
+ set interval(value) {
940
+ if (value != this._interval) {
941
+ this._interval = value;
942
+ if (this.running)
943
+ this.restart();
944
+ }
945
+ }
946
+ get callback() {
947
+ return this._callback;
948
+ }
949
+ set callback(value) {
950
+ if (value != this._callback) {
951
+ this._callback = value;
952
+ }
953
+ }
954
+ start() {
955
+ if (this._intervalId === null) {
956
+ this._intervalId = setInterval(() => {
957
+ if (this._callback != null)
958
+ this._callback();
959
+ }, this._interval);
960
+ }
961
+ }
962
+ stop() {
963
+ if (this._intervalId !== null) {
964
+ clearInterval(this._intervalId);
965
+ this._intervalId = null;
966
+ }
967
+ }
968
+ restart() {
969
+ this.stop();
970
+ this.start();
971
+ }
972
+ }
973
+
974
+ /**
975
+ * Represents a duration of time in milliseconds.
976
+ */
977
+ class TimeSpan {
978
+ constructor(milliseconds) {
979
+ this.milliseconds = milliseconds;
980
+ }
981
+ // Obtener el intervalo de tiempo en segundos
982
+ seconds() {
983
+ return this.milliseconds / 1000;
984
+ }
985
+ // Obtener el intervalo de tiempo en minutos
986
+ minutes() {
987
+ return this.milliseconds / (1000 * 60);
988
+ }
989
+ // Obtener el intervalo de tiempo en horas
990
+ hours() {
991
+ return this.milliseconds / (1000 * 60 * 60);
992
+ }
993
+ // Obtener el intervalo de tiempo en días
994
+ days() {
995
+ return this.milliseconds / (1000 * 60 * 60 * 24);
996
+ }
997
+ // Obtener el intervalo de tiempo en semanas
998
+ weeks() {
999
+ return this.milliseconds / (1000 * 60 * 60 * 24 * 7);
1000
+ }
1001
+ // Constructor estático para crear un TimeSpan desde milisegundos
1002
+ static fromMilliseconds(milliseconds) {
1003
+ return new TimeSpan(milliseconds);
1004
+ }
1005
+ // Constructor estático para crear un TimeSpan desde segundos
1006
+ static fromSeconds(seconds) {
1007
+ return new TimeSpan(seconds * 1000);
1008
+ }
1009
+ // Constructor estático para crear un TimeSpan desde minutos
1010
+ static fromMinutes(minutes) {
1011
+ return new TimeSpan(minutes * 1000 * 60);
1012
+ }
1013
+ // Constructor estático para crear un TimeSpan desde horas
1014
+ static fromHours(hours) {
1015
+ return new TimeSpan(hours * 1000 * 60 * 60);
1016
+ }
1017
+ // Constructor estático para crear un TimeSpan desde días
1018
+ static fromDays(days) {
1019
+ return new TimeSpan(days * 1000 * 60 * 60 * 24);
1020
+ }
1021
+ // Constructor estático para crear un TimeSpan desde semanas
1022
+ static fromWeeks(weeks) {
1023
+ return new TimeSpan(weeks * 1000 * 60 * 60 * 24 * 7);
1024
+ }
1025
+ // Añadir un intervalo de tiempo
1026
+ addMilliseconds(milliseconds) {
1027
+ return new TimeSpan(this.milliseconds + milliseconds);
1028
+ }
1029
+ addSeconds(seconds) {
1030
+ return this.addMilliseconds(seconds * 1000);
1031
+ }
1032
+ addMinutes(minutes) {
1033
+ return this.addMilliseconds(minutes * 1000 * 60);
1034
+ }
1035
+ addHours(hours) {
1036
+ return this.addMilliseconds(hours * 1000 * 60 * 60);
1037
+ }
1038
+ addDays(days) {
1039
+ return this.addMilliseconds(days * 1000 * 60 * 60 * 24);
1040
+ }
1041
+ addWeeks(weeks) {
1042
+ return this.addMilliseconds(weeks * 1000 * 60 * 60 * 24 * 7);
1043
+ }
1044
+ // Restar un intervalo de tiempo
1045
+ subtractMilliseconds(milliseconds) {
1046
+ return new TimeSpan(this.milliseconds - milliseconds);
1047
+ }
1048
+ subtractSeconds(seconds) {
1049
+ return this.subtractMilliseconds(seconds * 1000);
1050
+ }
1051
+ subtractMinutes(minutes) {
1052
+ return this.subtractMilliseconds(minutes * 1000 * 60);
1053
+ }
1054
+ subtractHours(hours) {
1055
+ return this.subtractMilliseconds(hours * 1000 * 60 * 60);
1056
+ }
1057
+ subtractDays(days) {
1058
+ return this.subtractMilliseconds(days * 1000 * 60 * 60 * 24);
1059
+ }
1060
+ subtractWeeks(weeks) {
1061
+ return this.subtractMilliseconds(weeks * 1000 * 60 * 60 * 24 * 7);
1062
+ }
1063
+ // Añadir otro TimeSpan
1064
+ add(other) {
1065
+ return new TimeSpan(this.milliseconds + other.milliseconds);
1066
+ }
1067
+ // Restar otro TimeSpan
1068
+ subtract(other) {
1069
+ return new TimeSpan(this.milliseconds - other.milliseconds);
1070
+ }
1071
+ // Añadir un intervalo de tiempo a una fecha
1072
+ addTo(date) {
1073
+ return new Date(date.getTime() + this.milliseconds);
1074
+ }
1075
+ // Restar un intervalo de tiempo de una fecha
1076
+ subtractFrom(date) {
1077
+ return new Date(date.getTime() - this.milliseconds);
1078
+ }
1079
+ static fromDifference(earlierDate, laterDate) {
1080
+ return new TimeSpan(laterDate.getTime() - earlierDate.getTime());
1081
+ }
1082
+ format(format = 'hh:mm:ss') {
1083
+ const formatLower = format.toLowerCase();
1084
+ const hasHours = formatLower.includes("h");
1085
+ const hasMinutes = formatLower.includes("m");
1086
+ let hours = 0, minutes = 0, seconds = Math.floor(this.milliseconds / 1000);
1087
+ if (hasHours) {
1088
+ hours = Math.floor(seconds / 3600);
1089
+ seconds -= hours * 3600;
1090
+ }
1091
+ if (hasMinutes) {
1092
+ minutes = Math.floor(seconds / 60);
1093
+ seconds -= minutes * 60;
1094
+ }
1095
+ const hoursPadded = String(hours).padStart(2, '0');
1096
+ const minutesPadded = String(minutes).padStart(2, '0');
1097
+ const secondsPadded = String(seconds).padStart(2, '0');
1098
+ return formatLower
1099
+ .replace('hh', hoursPadded)
1100
+ .replace('h', hours.toString())
1101
+ .replace('mm', minutesPadded)
1102
+ .replace('m', minutes.toString())
1103
+ .replace('ss', secondsPadded)
1104
+ .replace('s', seconds.toString());
1105
+ }
1106
+ eq(other) {
1107
+ return this.milliseconds === other.milliseconds;
1108
+ }
1109
+ le(other) {
1110
+ return this.milliseconds <= other.milliseconds;
1111
+ }
1112
+ lt(other) {
1113
+ return this.milliseconds < other.milliseconds;
1114
+ }
1115
+ ge(other) {
1116
+ return this.milliseconds >= other.milliseconds;
1117
+ }
1118
+ gt(other) {
1119
+ return this.milliseconds > other.milliseconds;
1120
+ }
1121
+ multiply(number) {
1122
+ return new TimeSpan(this.milliseconds * number);
1123
+ }
1124
+ divide(number) {
1125
+ return new TimeSpan(this.milliseconds / number);
1126
+ }
1127
+ abs() {
1128
+ return new TimeSpan(Math.abs(this.milliseconds));
1129
+ }
1130
+ isInfinite() {
1131
+ return this.milliseconds === Number.POSITIVE_INFINITY || this.milliseconds === Number.NEGATIVE_INFINITY;
1132
+ }
1133
+ // Determinar si es un TimeSpan infinitamente positivo
1134
+ isPositiveInfinite() {
1135
+ return this.milliseconds === Number.POSITIVE_INFINITY;
1136
+ }
1137
+ // Determinar si es un TimeSpan infinitamente negativo
1138
+ isNegativeInfinite() {
1139
+ return this.milliseconds === Number.NEGATIVE_INFINITY;
1140
+ }
1141
+ }
1142
+ TimeSpan.INFINITE = new TimeSpan(Number.POSITIVE_INFINITY);
1143
+ TimeSpan.NEGATIVE_INFINITE = new TimeSpan(Number.NEGATIVE_INFINITY);
1144
+
1145
+ /**
1146
+ * Represents a lazy value that is created only when it is accessed for the first time.
1147
+ * @template T The type of the lazy value.
1148
+ */
1149
+ class Lazy {
1150
+ constructor(getter) {
1151
+ this._valueCreated = false;
1152
+ this._value = null;
1153
+ this._factoryMethod = getter;
1154
+ }
1155
+ get valueCreated() {
1156
+ return this._valueCreated;
1157
+ }
1158
+ get value() {
1159
+ if (!this._valueCreated) {
1160
+ this._value = this._factoryMethod();
1161
+ this._valueCreated = true;
1162
+ }
1163
+ return this._value;
1164
+ }
1165
+ reset() {
1166
+ this._valueCreated = false;
1167
+ this._value = null;
1168
+ }
1169
+ }
1170
+
1171
+ /**
1172
+ * Represents a class for manipulating an array of items.
1173
+ *
1174
+ * @template T - The type of items in the array.
1175
+ */
1176
+ class ArrayManipulator {
1177
+ constructor(array) {
1178
+ this._array = array;
1179
+ }
1180
+ [Symbol.iterator]() {
1181
+ return this._array[Symbol.iterator]();
1182
+ }
1183
+ /**
1184
+ * Retrieves or sets the value at the specified index in the array.
1185
+ * If `item` is not provided, returns the value at index `n`.
1186
+ * If `item` is provided, sets the value at index `n` to the provided value.
1187
+ *
1188
+ * @param {number} n - The index at which to retrieve or set the value.
1189
+ * @param {T | undefined} [item] - The value to set at index `n`, if provided.
1190
+ *
1191
+ * @return {T | void} - If `item` is not provided, returns the value at index `n`.
1192
+ * - If `item` is provided, does not return anything.
1193
+ */
1194
+ at(n, item = undefined) {
1195
+ if (item === undefined)
1196
+ return this._array[n];
1197
+ else
1198
+ this._array[n] = item;
1199
+ }
1200
+ /**
1201
+ * Removes the specified item from the array.
1202
+ *
1203
+ * @param {T} item - The item to be removed.
1204
+ * @returns {ArrayManipulator<T>} - The updated ArrayManipulator instance.
1205
+ */
1206
+ remove(item) {
1207
+ const index = this._array.indexOf(item);
1208
+ if (index !== -1) {
1209
+ this._array.splice(index, 1);
1210
+ }
1211
+ return this;
1212
+ }
1213
+ /**
1214
+ * Applies a mapping function to each element in the array, transforming it into a new array.
1215
+ * @template R
1216
+ * @param {UnaryFunction<T, R>} mapFn - The function to be applied to each element.
1217
+ * @return {ArrayManipulator<R>} - The new ArrayManipulator instance with the mapped elements.
1218
+ */
1219
+ map(mapFn) {
1220
+ for (let i = 0; i < this._array.length; i++) {
1221
+ this._array[i] = mapFn(this._array[i]);
1222
+ }
1223
+ return this;
1224
+ }
1225
+ /**
1226
+ * Filters the elements of the array based on a given filter function.
1227
+ * The filter function should return a boolean value, indicating whether the element should be included in the filtered array or not.
1228
+ *
1229
+ * @param {Predicate<T>} filterFn - The function that will be used to filter the elements. It should accept an element of type T and return a boolean value.
1230
+ * @returns {ArrayManipulator<T>} - The filtered ArrayManipulator instance with the elements that passed the filter.
1231
+ */
1232
+ filter(filterFn) {
1233
+ for (let i = 0; i < this._array.length; i++) {
1234
+ if (!filterFn(this._array[i])) {
1235
+ this._array.splice(i, 1);
1236
+ i--;
1237
+ }
1238
+ }
1239
+ return this;
1240
+ }
1241
+ head(n) {
1242
+ this._array.splice(n);
1243
+ return this;
1244
+ }
1245
+ slice(start, count = undefined) {
1246
+ this._array.splice(0, start); // Eliminar los primeros elementos hasta `start`
1247
+ if (count !== undefined) {
1248
+ this._array.splice(count); // Mantener solo `count` elementos restantes
1249
+ }
1250
+ return this;
1251
+ }
1252
+ mapMany(mapper) {
1253
+ let i = 0;
1254
+ while (i < this._array.length) {
1255
+ let mappedItems = mapper(this._array[i]);
1256
+ if (!Array.isArray(mappedItems))
1257
+ mappedItems = Array.from(mappedItems);
1258
+ this._array.splice(i, 1, ...mappedItems);
1259
+ i += mappedItems.length;
1260
+ }
1261
+ return this;
1262
+ }
1263
+ tail(n) {
1264
+ const start = this._array.length - n;
1265
+ this._array.splice(0, start);
1266
+ return this;
1267
+ }
1268
+ /**
1269
+ * Appends one or more items to the array.
1270
+ *
1271
+ * @param {...T} items - The items to be appended to the array.
1272
+ * @return {ArrayManipulator<T>} - The ArrayManipulator instance.
1273
+ */
1274
+ append(...items) {
1275
+ this._array.push(...items);
1276
+ return this;
1277
+ }
1278
+ /**
1279
+ * Prepend items to the beginning of the array.
1280
+ *
1281
+ * @param {...T} items - The items to be prepended.
1282
+ * @return {ArrayManipulator<T>} The ArrayManipulator instance.
1283
+ */
1284
+ prepend(...items) {
1285
+ this._array.unshift(...items);
1286
+ return this;
1287
+ }
1288
+ get array() {
1289
+ return this._array;
1290
+ }
1291
+ }
1292
+ /**
1293
+ * Creates an instance of ArrayManipulator with the given array.
1294
+ * @template T
1295
+ * @param {T[]} array - The input array.
1296
+ * @return {ArrayManipulator<T>} - An instance of the ArrayManipulator class.
1297
+ */
1298
+ function array(array) {
1299
+ return new ArrayManipulator(array);
1300
+ }
1301
+
1302
+ exports.ArrayManipulator = ArrayManipulator;
1303
+ exports.CacheDictionary = CacheDictionary;
1304
+ exports.From = From;
1305
+ exports.Lazy = Lazy;
1306
+ exports.Pair = Pair;
1307
+ exports.TimeSpan = TimeSpan;
1308
+ exports.Timer = Timer;
1309
+ exports.ajaxSubmission = ajaxSubmission;
1310
+ exports.ajaxSubmit = ajaxSubmit;
1311
+ exports.array = array;
1312
+ exports.clamp = clamp;
1313
+ exports.deepClone = deepClone;
1314
+ exports.ensurePrefix = ensurePrefix;
1315
+ exports.ensureSuffix = ensureSuffix;
1316
+ exports.format = format;
1317
+ exports.from = from;
1318
+ exports.getType = getType;
1319
+ exports.isArray = isArray;
1320
+ exports.isBigInt = isBigInt;
1321
+ exports.isBoolean = isBoolean;
1322
+ exports.isDefined = isDefined;
1323
+ exports.isEmpty = isEmpty;
1324
+ exports.isEmptyOrWhitespace = isEmptyOrWhitespace;
1325
+ exports.isFunction = isFunction;
1326
+ exports.isIterable = isIterable;
1327
+ exports.isNull = isNull;
1328
+ exports.isNullOrUndefined = isNullOrUndefined;
1329
+ exports.isNumber = isNumber;
1330
+ exports.isObject = isObject;
1331
+ exports.isString = isString;
1332
+ exports.isSymbol = isSymbol;
1333
+ exports.isUndefined = isUndefined;
1334
+ exports.lerp = lerp;
1335
+ exports.objectToFormData = objectToFormData;
1336
+ exports.promisify = promisify;
1337
+ exports.toPairs = toPairs;
1338
+
1339
+ })(this.window = this.window || {});