@zelgadis87/utils-core 5.4.0 → 5.4.2

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.
@@ -181,8 +181,8 @@ type TOptional<T> = {
181
181
  orElseReturnNullableAndApply: (newValue: T | null | undefined) => TOptional<T>;
182
182
  orElseProduceNullableAndApply: (newValueProducer: TProducer<T | null | undefined>) => TOptional<T>;
183
183
  orElseThrow: (errorProducer: TProducer<Error>) => TPresentOptional<T>;
184
- mapTo<R>(mapper: TFunction<T, R>): TOptional<R>;
185
- flatMapTo<R>(mapper: TFunction<T, TOptional<R>>): TOptional<R>;
184
+ mapTo<R>(mapper: TFunction<T, R>): TPresentOptional<R> | TEmptyOptional<T>;
185
+ flatMapTo<R>(mapper: TFunction<T, TOptional<R>>): TOptional<R> | TEmptyOptional<T>;
186
186
  filter(predicate: TPredicate<T>): TOptional<T>;
187
187
  };
188
188
  type TEmptyOptional<T> = TOptional<T> & {
@@ -190,12 +190,33 @@ type TEmptyOptional<T> = TOptional<T> & {
190
190
  isEmpty(): true;
191
191
  isPresent(): false;
192
192
  apply<RP = void, RE = void>(callbackIfPresent: TFunction<T, RP>, callbackIfEmpty: TProducer<RE>): RE;
193
+ mapTo<R>(mapper: TFunction<T, R>): TEmptyOptional<T>;
194
+ flatMapTo<R>(mapper: TFunction<T, TOptional<R>>): TEmptyOptional<T>;
195
+ filter(predicate: TPredicate<T>): TEmptyOptional<T>;
196
+ orElseReturn: <R>(newValue: R) => R;
197
+ orElseProduce: <R>(newValueProducer: TProducer<R>) => R;
198
+ orElseReturnNullable: <R>(newValue: R | null | undefined) => TOptional<R>;
199
+ orElseProduceNullable: <R>(newValueProducer: TProducer<R | null | undefined>) => TOptional<R>;
200
+ orElseReturnAndApply: <R>(newValue: R) => R;
201
+ orElseProduceAndApply: <R>(newValueProducer: TProducer<R>) => R;
202
+ orElseReturnNullableAndApply: <R>(newValue: R | null | undefined) => TOptional<R>;
203
+ orElseProduceNullableAndApply: <R>(newValueProducer: TProducer<R | null | undefined>) => TOptional<R>;
193
204
  };
194
205
  type TPresentOptional<T> = TOptional<T> & {
195
206
  get(): T;
196
207
  isEmpty(): false;
197
208
  isPresent(): true;
198
209
  apply<RP = void, RE = void>(callbackIfPresent: TFunction<T, RP>, callbackIfEmpty: TProducer<RE>): RP;
210
+ mapTo<R>(mapper: TFunction<T, R>): TPresentOptional<R>;
211
+ flatMapTo<R>(mapper: TFunction<T, TOptional<R>>): TOptional<R>;
212
+ orElseReturn: (newValue: T) => T;
213
+ orElseProduce: (newValueProducer: TProducer<T>) => T;
214
+ orElseReturnNullable: (newValue: T | null | undefined) => TOptional<T>;
215
+ orElseProduceNullable: (newValueProducer: TProducer<T | null | undefined>) => TOptional<T>;
216
+ orElseReturnAndApply: (newValue: T) => T;
217
+ orElseProduceAndApply: (newValueProducer: TProducer<T>) => T;
218
+ orElseReturnNullableAndApply: (newValue: T | null | undefined) => TOptional<T>;
219
+ orElseProduceNullableAndApply: (newValueProducer: TProducer<T | null | undefined>) => TOptional<T>;
199
220
  };
200
221
  declare class ErrorGetEmptyOptional extends Error {
201
222
  constructor();
@@ -893,7 +914,7 @@ declare function filterMapReduce<T, U, R>(array: T[], filterFn: TPredicate<T>, m
893
914
  * @param predicate the predicate to use to partition the array
894
915
  * @returns a tuple, where the first array contains items matching the predicate, and the second array contains items not matching the predicate.
895
916
  */
896
- declare function partition<T>(arr: T[], predicate: TPredicate<T>): [T[], T[]];
917
+ declare function partition<T>(arr: TReadableArray<T>, predicate: TPredicate<T>): [T[], T[]];
897
918
  /**
898
919
  * Maps the first truthy value in the array using the provided mapping function.
899
920
  * @param arr - The array of items.
@@ -1021,16 +1042,21 @@ type TIsEmptyObject<T> = keyof T extends never ? true : false;
1021
1042
  type TConditionalOptionalType<T> = TIsEmptyObject<T> extends true ? [] : [T];
1022
1043
  type TEmptyObject = Record<string, never>;
1023
1044
 
1024
- type TOperation<T, E = Error> = {
1045
+ type TOperationFailure<E = Error> = {
1025
1046
  success: false;
1026
1047
  error: E;
1027
- } | {
1048
+ };
1049
+ type TOperationSuccess<T> = {
1028
1050
  success: true;
1029
1051
  data: T;
1030
1052
  };
1053
+ type TOperation<T, E = Error> = TOperationFailure<E> | TOperationSuccess<T>;
1031
1054
  type TAsyncOperation<T, E = Error> = Promise<TOperation<T, E>>;
1032
1055
  type TOperationTuple<T, E = Error> = [T, undefined] | [undefined, E];
1033
1056
  type TAsyncOperationTuple<T, E = Error> = Promise<TOperationTuple<T, E>>;
1057
+ /**
1058
+ * @deprecated Use `TOperation<T, OperationAggregateError<E>>` with `Operation.combine` instead.
1059
+ */
1034
1060
  type TValidation<T, E = Error> = {
1035
1061
  success: false;
1036
1062
  errors: E[];
@@ -1038,7 +1064,24 @@ type TValidation<T, E = Error> = {
1038
1064
  success: true;
1039
1065
  data: T;
1040
1066
  };
1067
+ /**
1068
+ * @deprecated Use `TAsyncOperation<T, OperationAggregateError<E>>` with `Operation.combine` instead.
1069
+ */
1041
1070
  type TAsyncValidation<T, E = Error> = Promise<TValidation<T, E>>;
1071
+ /**
1072
+ * An error class that aggregates multiple errors from a combined operation.
1073
+ * Used by `Operation.combine` to represent failures from multiple operations.
1074
+ *
1075
+ * @template E - The type of individual errors (defaults to Error, but can be any type)
1076
+ */
1077
+ declare class OperationAggregateError<E = Error> extends Error {
1078
+ readonly errors: E[];
1079
+ constructor(errors: E[]);
1080
+ /**
1081
+ * Returns the number of aggregated errors.
1082
+ */
1083
+ get count(): number;
1084
+ }
1042
1085
  declare const Operation: {
1043
1086
  ok: <const T>(data: T) => {
1044
1087
  readonly success: true;
@@ -1048,6 +1091,44 @@ declare const Operation: {
1048
1091
  readonly success: false;
1049
1092
  readonly error: E;
1050
1093
  };
1094
+ /**
1095
+ * Type predicate that returns true if the operation is a success.
1096
+ * Useful for type narrowing in conditional blocks.
1097
+ *
1098
+ * @template T - The success data type
1099
+ * @param result - The operation result to check
1100
+ * @returns true if the operation succeeded, false otherwise
1101
+ */
1102
+ isSuccess<T>(result: TOperation<T, unknown>): result is TOperationSuccess<T>;
1103
+ /**
1104
+ * Type predicate that returns true if the operation is a failure.
1105
+ * Useful for type narrowing in conditional blocks.
1106
+ *
1107
+ * @template E - The error type
1108
+ * @param result - The operation result to check
1109
+ * @returns true if the operation failed, false otherwise
1110
+ */
1111
+ isFailure<E>(result: TOperation<unknown, E>): result is TOperationFailure<E>;
1112
+ /**
1113
+ * Partitions an array of operations into successes and failures.
1114
+ *
1115
+ * @template T - The success data type of individual operations
1116
+ * @template E - The error type of individual operations (defaults to Error)
1117
+ * @param results - Array of operation results to partition
1118
+ * @returns A tuple of [successes, failures]
1119
+ */
1120
+ partition: <T, E = Error>(results: TReadableArray<TOperation<T, E>>) => [TOperationSuccess<T>[], TOperationFailure<E>[]];
1121
+ /**
1122
+ * Combines multiple operation results into a single result.
1123
+ * - If all operations succeed, returns success with an array of all data values.
1124
+ * - If any operation fails, returns failure with an `OperationAggregateError` containing all errors.
1125
+ *
1126
+ * @template T - The success data type of individual operations
1127
+ * @template E - The error type of individual operations (defaults to Error)
1128
+ * @param results - Array of operation results to combine
1129
+ * @returns A single operation with either all data or all aggregated errors
1130
+ */
1131
+ combine: <T, E = Error>(results: TReadableArray<TOperation<T, E>>) => TOperation<T[], OperationAggregateError<E>>;
1051
1132
  };
1052
1133
 
1053
1134
  declare function withTryCatch<R>(fn: TFunction<void, R>, errMapFn?: TTransformer<Error, Error>): TOperationTuple<R, Error>;
@@ -1504,5 +1585,5 @@ declare class DataUpgrader<X extends TUpgradable, XLatest extends X> implements
1504
1585
  }
1505
1586
  declare function isUpgradable(obj: TJsonSerializable): obj is TUpgradable;
1506
1587
 
1507
- export { Cached, DataUpgrader, Deferred, DeferredCanceledError, ErrorCannotInstantiatePresentOptionalWithEmptyValue, ErrorGetEmptyOptional, ErrorSetEmptyOptional, Lazy, LazyAsync, LazyDictionary, Logger, NEVER, NonExhaustiveSwitchError, Operation, Optional, PredicateBuilder, RandomTimeDuration, RateThrottler, Semaphore, Sorter, StringParts, TimeDuration, TimeFrequency, TimeInstant, TimeRange, TimeUnit, TimeoutError, alwaysFalse, alwaysTrue, and, arrayGet, arrayIncludes, asError, asPromise, average, averageBy, awaitAtMost, capitalizeWord, clamp, clampInt0_100, constant, constantFalse, constantNull, constantOne, constantTrue, constantUndefined, constantZero, cssDeclarationRulesDictionaryToCss, decrement, decrementBy, delayPromise, dictToEntries, dictToList, divideBy, ellipsis, ensureArray, ensureDefined, ensureNegativeNumber, ensureNonNegativeNumber, ensureNonPositiveNumber, ensurePositiveNumber, ensureReadableArray, entriesToDict, entriesToEntries, entriesToList, extendArray, extendArrayWith, fill, fillWith, filterMap, filterMapReduce, filterWithTypePredicate, findInArray, findIndexInArray, first, flatMapTruthys, getCauseMessageFromError, getCauseStackFromError, getMessageFromError, getStackFromError, groupByBoolean, groupByBooleanWith, groupByNumber, groupByNumberWith, groupByString, groupByStringWith, groupBySymbol, groupBySymbolWith, hashCode, havingMaxBy, havingMinBy, head, identity, ifDefined, ifNullOrUndefined, iff, includes, increment, incrementBy, indexByNumber, indexByNumberWith, indexByString, indexByStringWith, indexBySymbol, indexBySymbolWith, indexByWith, isAllowedTimeDuration, isArray, isDefined, isEmpty, isError, isFalse, isFunction, isNegativeNumber, isNullOrUndefined, isNullOrUndefinedOrEmpty, isNumber, isPositiveNumber, isString, isTimeInstant, isTrue, isUpgradable, isZero, jsonCloneDeep, last, listToDict, mapDefined, mapEntries, mapFirstTruthy, mapTruthys, max, maxBy, min, minBy, multiplyBy, noop, not, omitFromJsonObject, or, pad, padLeft, padRight, parseJson, parseTimeInstantBasicComponents, parseTimeInstantComponents, partition, pick, pipedInvoke, pipedInvokeFromArray, pluralize, promiseSequence, randomDecimalInInterval, randomId, randomIntegerInInterval, randomNumberInInterval, randomPick, randomPicks, range, repeat, reverse, round, roundAwayFromZero, roundToLower, roundToNearest, roundToUpper, roundTowardsZero, shallowArrayEquals, shallowRecordEquals, sortedArray, splitWords, stringToNumber, stringifyJson, sum, sumBy, tail, throttle, throwIfNullOrUndefined, transformCssDictionary, tryToParseJson, tryToParseNumber, uniq, uniqBy, uniqByKey, unzip, upsert, withTryCatch, withTryCatchAsync, wrapWithString, xor, zip };
1508
- export type { ICancelable, ICancelablePromise, IDataUpgrader, TAccumulator, TAllKeysOptional, TAnyFunction, TArrayable, TAsyncAnyFunction, TAsyncBiConsumer, TAsyncBiFunction, TAsyncBiPredicate, TAsyncConsumer, TAsyncFunction, TAsyncOperation, TAsyncOperationTuple, TAsyncPredicate, TAsyncProducer, TAsyncValidation, TAsyncVoidFunction, TBasicTimePattern, TBiConsumer, TBiFunction, TBiPredicate, TComparisonDirection, TComparisonFunction, TComparisonResult, TConditionalOptionalType, TConditionalParameter, TConditionalParameterOptions, TConsumer, TCssDeclarationRulesDictionary, TCssSelectorDeclarationRulesDictionary, TDayOfMonth, TDayOfWeek, TDigit, TDigit1_9, TEmpty, TEmptyArray, TEmptyObject, TEmptyOptional, TFourDigits, TFourDigitsMillisecond, TFourDigitsYear, TFunction, THasNever, THourOfDay, THtmlString, TIdentityFunction, TIntervalHandle, TIsEmptyObject, TIso8601DateString, TIso8601DateUtcString, TJsonArray, TJsonObject, TJsonPrimitive, TJsonSerializable, TKeysOfType, TLoggerOpts, TMaybe, TMillisecondOfSecond, TMinuteOfHour, TMonth, TMonthName, TNegativeNumber, TNumber0_10, TNumber0_100, TNumber0_1000, TNumber0_15, TNumber0_20, TNumber0_5, TNumber1_10, TNumericFloatingPointString, TNumericString, TOneDigit, TOperation, TOperationTuple, TOptional, TOptionalKeysForType, TOptionsWithoutDefaults, TParseInt, TParseableInt, TPositiveNumber, TPredefinedTimeDuration, TPredicate, TPresentOptional, TPrettify, TPrimitive, TProducer, TPromisable, TReadableArray, TRelativeUrl, TReplaceType, TRequiredKeysForType, TSecondOfMinute, TSorter, TSorterBuilder, TStrictComparisonResult, TThreeDigits, TThreeDigitsMillisecond, TTimeInUnits, TTimeoutHandle, TTransformer, TTwoDigits, TTwoDigitsDate, TTwoDigitsHour, TTwoDigitsMinute, TTwoDigitsMonth, TTwoDigitsSecond, TTypePredicate, TUpToFourDigits, TUpToThreeDigits, TUpToTwoDigits, TUpgradable, TUrl, TValidTimeDuration, TValidation, TVoidFunction, TWeekNumber, TWithExtras, TWithRequiredProperties, TWithRequiredProperty, TYear, TZero };
1588
+ export { Cached, DataUpgrader, Deferred, DeferredCanceledError, ErrorCannotInstantiatePresentOptionalWithEmptyValue, ErrorGetEmptyOptional, ErrorSetEmptyOptional, Lazy, LazyAsync, LazyDictionary, Logger, NEVER, NonExhaustiveSwitchError, Operation, OperationAggregateError, Optional, PredicateBuilder, RandomTimeDuration, RateThrottler, Semaphore, Sorter, StringParts, TimeDuration, TimeFrequency, TimeInstant, TimeRange, TimeUnit, TimeoutError, alwaysFalse, alwaysTrue, and, arrayGet, arrayIncludes, asError, asPromise, average, averageBy, awaitAtMost, capitalizeWord, clamp, clampInt0_100, constant, constantFalse, constantNull, constantOne, constantTrue, constantUndefined, constantZero, cssDeclarationRulesDictionaryToCss, decrement, decrementBy, delayPromise, dictToEntries, dictToList, divideBy, ellipsis, ensureArray, ensureDefined, ensureNegativeNumber, ensureNonNegativeNumber, ensureNonPositiveNumber, ensurePositiveNumber, ensureReadableArray, entriesToDict, entriesToEntries, entriesToList, extendArray, extendArrayWith, fill, fillWith, filterMap, filterMapReduce, filterWithTypePredicate, findInArray, findIndexInArray, first, flatMapTruthys, getCauseMessageFromError, getCauseStackFromError, getMessageFromError, getStackFromError, groupByBoolean, groupByBooleanWith, groupByNumber, groupByNumberWith, groupByString, groupByStringWith, groupBySymbol, groupBySymbolWith, hashCode, havingMaxBy, havingMinBy, head, identity, ifDefined, ifNullOrUndefined, iff, includes, increment, incrementBy, indexByNumber, indexByNumberWith, indexByString, indexByStringWith, indexBySymbol, indexBySymbolWith, indexByWith, isAllowedTimeDuration, isArray, isDefined, isEmpty, isError, isFalse, isFunction, isNegativeNumber, isNullOrUndefined, isNullOrUndefinedOrEmpty, isNumber, isPositiveNumber, isString, isTimeInstant, isTrue, isUpgradable, isZero, jsonCloneDeep, last, listToDict, mapDefined, mapEntries, mapFirstTruthy, mapTruthys, max, maxBy, min, minBy, multiplyBy, noop, not, omitFromJsonObject, or, pad, padLeft, padRight, parseJson, parseTimeInstantBasicComponents, parseTimeInstantComponents, partition, pick, pipedInvoke, pipedInvokeFromArray, pluralize, promiseSequence, randomDecimalInInterval, randomId, randomIntegerInInterval, randomNumberInInterval, randomPick, randomPicks, range, repeat, reverse, round, roundAwayFromZero, roundToLower, roundToNearest, roundToUpper, roundTowardsZero, shallowArrayEquals, shallowRecordEquals, sortedArray, splitWords, stringToNumber, stringifyJson, sum, sumBy, tail, throttle, throwIfNullOrUndefined, transformCssDictionary, tryToParseJson, tryToParseNumber, uniq, uniqBy, uniqByKey, unzip, upsert, withTryCatch, withTryCatchAsync, wrapWithString, xor, zip };
1589
+ export type { ICancelable, ICancelablePromise, IDataUpgrader, TAccumulator, TAllKeysOptional, TAnyFunction, TArrayable, TAsyncAnyFunction, TAsyncBiConsumer, TAsyncBiFunction, TAsyncBiPredicate, TAsyncConsumer, TAsyncFunction, TAsyncOperation, TAsyncOperationTuple, TAsyncPredicate, TAsyncProducer, TAsyncValidation, TAsyncVoidFunction, TBasicTimePattern, TBiConsumer, TBiFunction, TBiPredicate, TComparisonDirection, TComparisonFunction, TComparisonResult, TConditionalOptionalType, TConditionalParameter, TConditionalParameterOptions, TConsumer, TCssDeclarationRulesDictionary, TCssSelectorDeclarationRulesDictionary, TDayOfMonth, TDayOfWeek, TDigit, TDigit1_9, TEmpty, TEmptyArray, TEmptyObject, TEmptyOptional, TFourDigits, TFourDigitsMillisecond, TFourDigitsYear, TFunction, THasNever, THourOfDay, THtmlString, TIdentityFunction, TIntervalHandle, TIsEmptyObject, TIso8601DateString, TIso8601DateUtcString, TJsonArray, TJsonObject, TJsonPrimitive, TJsonSerializable, TKeysOfType, TLoggerOpts, TMaybe, TMillisecondOfSecond, TMinuteOfHour, TMonth, TMonthName, TNegativeNumber, TNumber0_10, TNumber0_100, TNumber0_1000, TNumber0_15, TNumber0_20, TNumber0_5, TNumber1_10, TNumericFloatingPointString, TNumericString, TOneDigit, TOperation, TOperationFailure, TOperationSuccess, TOperationTuple, TOptional, TOptionalKeysForType, TOptionsWithoutDefaults, TParseInt, TParseableInt, TPositiveNumber, TPredefinedTimeDuration, TPredicate, TPresentOptional, TPrettify, TPrimitive, TProducer, TPromisable, TReadableArray, TRelativeUrl, TReplaceType, TRequiredKeysForType, TSecondOfMinute, TSorter, TSorterBuilder, TStrictComparisonResult, TThreeDigits, TThreeDigitsMillisecond, TTimeInUnits, TTimeoutHandle, TTransformer, TTwoDigits, TTwoDigitsDate, TTwoDigitsHour, TTwoDigitsMinute, TTwoDigitsMonth, TTwoDigitsSecond, TTypePredicate, TUpToFourDigits, TUpToThreeDigits, TUpToTwoDigits, TUpgradable, TUrl, TValidTimeDuration, TValidation, TVoidFunction, TWeekNumber, TWithExtras, TWithRequiredProperties, TWithRequiredProperty, TYear, TZero };
package/.rollup/index.mjs CHANGED
@@ -776,9 +776,9 @@ function filterMapReduce(array, filterFn, mapFn, reduceFn, initialValue) {
776
776
  * @returns a tuple, where the first array contains items matching the predicate, and the second array contains items not matching the predicate.
777
777
  */
778
778
  function partition(arr, predicate) {
779
- return arr.reduce((partition, item) => {
780
- partition[(predicate(item) ? 0 : 1)].push(item);
781
- return partition;
779
+ return [...arr].reduce((acc, item) => {
780
+ acc[(predicate(item) ? 0 : 1)].push(item);
781
+ return acc;
782
782
  }, [[], []]);
783
783
  }
784
784
  /**
@@ -1101,130 +1101,6 @@ function tryToParseNumber(numberStr) {
1101
1101
  });
1102
1102
  }
1103
1103
 
1104
- const Operation = {
1105
- ok: (data) => {
1106
- return { success: true, data };
1107
- },
1108
- ko: (error) => {
1109
- return { success: false, error };
1110
- },
1111
- };
1112
-
1113
- function asPromise(promisable) {
1114
- return Promise.resolve(promisable);
1115
- }
1116
- function promiseSequence(...fns) {
1117
- const fn = async function () {
1118
- const results = [];
1119
- for (let i = 0; i < fns.length; i++) {
1120
- results[i] = await fns[i]();
1121
- }
1122
- return results;
1123
- };
1124
- return fn;
1125
- }
1126
- function delayPromise(duration) {
1127
- return (result) => duration.promise().then(() => result);
1128
- }
1129
- class TimeoutError extends Error {
1130
- }
1131
- async function awaitAtMost(promise, duration) {
1132
- return Promise.race([
1133
- promise.then(value => ({ status: 'ok', value })),
1134
- duration.promise().then(() => ({ status: 'timeout' }))
1135
- ]).then(({ status, value }) => {
1136
- if (status === 'ok')
1137
- return value;
1138
- throw new TimeoutError("Time out reached while waiting for a promise to resolve.");
1139
- });
1140
- }
1141
- const NEVER = new Promise(_resolve => { });
1142
-
1143
- /**
1144
- * Returns a random integer in the range [min, max].
1145
- * @deprecated Use randomIntegerInInterval or randomDecimalInInterval instead
1146
- */
1147
- function randomNumberInInterval(min, max) {
1148
- return Math.floor(Math.random() * (max - min + 1) + min);
1149
- }
1150
- /**
1151
- * Returns a random integer in the range [min, max].
1152
- * @param min - Minimum value (inclusive)
1153
- * @param max - Maximum value (inclusive)
1154
- * @returns A random integer between min and max
1155
- */
1156
- function randomIntegerInInterval(min, max) {
1157
- return Math.floor(Math.random() * (max - min + 1) + min);
1158
- }
1159
- /**
1160
- * Returns a random decimal in the range [min, max).
1161
- * @param min - Minimum value (inclusive)
1162
- * @param max - Maximum value (exclusive)
1163
- * @returns A random decimal between min and max
1164
- */
1165
- function randomDecimalInInterval(min, max) {
1166
- return Math.random() * (max - min) + min;
1167
- }
1168
- const randomId = (length) => {
1169
- const characters = 'abcdefghijklmnopqrstuvwxyz0123456789';
1170
- let result = '';
1171
- for (let i = 0; i < length; i++) {
1172
- result += characters.charAt(randomIntegerInInterval(0, characters.length - 1));
1173
- }
1174
- return result;
1175
- };
1176
- function randomPick(arr) {
1177
- return first$1(randomPicks(arr, 1));
1178
- }
1179
- function randomPicks(arr, count) {
1180
- const available = [...arr];
1181
- const result = [];
1182
- while (available.length > 0 && count > 0) {
1183
- const randomIndex = randomIntegerInInterval(0, available.length - 1);
1184
- result.push(available[randomIndex]);
1185
- available.splice(randomIndex, 1);
1186
- count--;
1187
- }
1188
- return result;
1189
- }
1190
-
1191
- function dictToEntries(obj) {
1192
- return Object.entries(obj);
1193
- }
1194
- function entriesToDict(entries) {
1195
- return Object.fromEntries(entries);
1196
- }
1197
- function entriesToEntries(dict, mapper) {
1198
- return entriesToDict(dictToEntries(dict).map((entry) => mapper(entry)));
1199
- }
1200
- /** @deprecated[2025.08.01]: Compatibility layer. */
1201
- const mapEntries = entriesToEntries;
1202
- function entriesToList(dict, mapper) {
1203
- return dictToEntries(dict).map((entry) => mapper(entry));
1204
- }
1205
-
1206
- function dictToList(obj) {
1207
- return Object.keys(obj).map(key => obj[key]);
1208
- }
1209
- function pick(o, keys) {
1210
- return keys.reduce((obj, key) => {
1211
- obj[key] = o[key];
1212
- return obj;
1213
- }, {});
1214
- }
1215
- function shallowRecordEquals(a, b) {
1216
- if (a === b)
1217
- return true;
1218
- const aKeys = Object.keys(a), bKeys = Object.keys(b);
1219
- if (aKeys.length !== bKeys.length)
1220
- return false;
1221
- for (const key of aKeys) {
1222
- if (a[key] !== b[key])
1223
- return false;
1224
- }
1225
- return true;
1226
- }
1227
-
1228
1104
  class StringParts {
1229
1105
  _parts;
1230
1106
  constructor(...parts) {
@@ -1397,6 +1273,197 @@ function wrapWithString(str, start, end = start) {
1397
1273
  return start + str + end;
1398
1274
  }
1399
1275
 
1276
+ /**
1277
+ * An error class that aggregates multiple errors from a combined operation.
1278
+ * Used by `Operation.combine` to represent failures from multiple operations.
1279
+ *
1280
+ * @template E - The type of individual errors (defaults to Error, but can be any type)
1281
+ */
1282
+ class OperationAggregateError extends Error {
1283
+ errors;
1284
+ constructor(errors) {
1285
+ super(`Operation failed with ${pluralize(errors.length, 'error')}`);
1286
+ this.errors = errors;
1287
+ this.name = 'OperationAggregateError';
1288
+ }
1289
+ /**
1290
+ * Returns the number of aggregated errors.
1291
+ */
1292
+ get count() {
1293
+ return this.errors.length;
1294
+ }
1295
+ }
1296
+ const Operation = {
1297
+ ok: (data) => {
1298
+ return { success: true, data };
1299
+ },
1300
+ ko: (error) => {
1301
+ return { success: false, error };
1302
+ },
1303
+ /**
1304
+ * Type predicate that returns true if the operation is a success.
1305
+ * Useful for type narrowing in conditional blocks.
1306
+ *
1307
+ * @template T - The success data type
1308
+ * @param result - The operation result to check
1309
+ * @returns true if the operation succeeded, false otherwise
1310
+ */
1311
+ isSuccess(result) {
1312
+ return result.success === true;
1313
+ },
1314
+ /**
1315
+ * Type predicate that returns true if the operation is a failure.
1316
+ * Useful for type narrowing in conditional blocks.
1317
+ *
1318
+ * @template E - The error type
1319
+ * @param result - The operation result to check
1320
+ * @returns true if the operation failed, false otherwise
1321
+ */
1322
+ isFailure(result) {
1323
+ return result.success === false;
1324
+ },
1325
+ /**
1326
+ * Partitions an array of operations into successes and failures.
1327
+ *
1328
+ * @template T - The success data type of individual operations
1329
+ * @template E - The error type of individual operations (defaults to Error)
1330
+ * @param results - Array of operation results to partition
1331
+ * @returns A tuple of [successes, failures]
1332
+ */
1333
+ partition: (results) => {
1334
+ return partition(results, r => r.success);
1335
+ },
1336
+ /**
1337
+ * Combines multiple operation results into a single result.
1338
+ * - If all operations succeed, returns success with an array of all data values.
1339
+ * - If any operation fails, returns failure with an `OperationAggregateError` containing all errors.
1340
+ *
1341
+ * @template T - The success data type of individual operations
1342
+ * @template E - The error type of individual operations (defaults to Error)
1343
+ * @param results - Array of operation results to combine
1344
+ * @returns A single operation with either all data or all aggregated errors
1345
+ */
1346
+ combine: (results) => {
1347
+ const [successes, failures] = Operation.partition(results);
1348
+ return failures.length === 0 ? Operation.ok(successes.map(r => r.data)) : Operation.ko(new OperationAggregateError(failures.map(r => r.error)));
1349
+ },
1350
+ };
1351
+
1352
+ function asPromise(promisable) {
1353
+ return Promise.resolve(promisable);
1354
+ }
1355
+ function promiseSequence(...fns) {
1356
+ const fn = async function () {
1357
+ const results = [];
1358
+ for (let i = 0; i < fns.length; i++) {
1359
+ results[i] = await fns[i]();
1360
+ }
1361
+ return results;
1362
+ };
1363
+ return fn;
1364
+ }
1365
+ function delayPromise(duration) {
1366
+ return (result) => duration.promise().then(() => result);
1367
+ }
1368
+ class TimeoutError extends Error {
1369
+ }
1370
+ async function awaitAtMost(promise, duration) {
1371
+ return Promise.race([
1372
+ promise.then(value => ({ status: 'ok', value })),
1373
+ duration.promise().then(() => ({ status: 'timeout' }))
1374
+ ]).then(({ status, value }) => {
1375
+ if (status === 'ok')
1376
+ return value;
1377
+ throw new TimeoutError("Time out reached while waiting for a promise to resolve.");
1378
+ });
1379
+ }
1380
+ const NEVER = new Promise(_resolve => { });
1381
+
1382
+ /**
1383
+ * Returns a random integer in the range [min, max].
1384
+ * @deprecated Use randomIntegerInInterval or randomDecimalInInterval instead
1385
+ */
1386
+ function randomNumberInInterval(min, max) {
1387
+ return Math.floor(Math.random() * (max - min + 1) + min);
1388
+ }
1389
+ /**
1390
+ * Returns a random integer in the range [min, max].
1391
+ * @param min - Minimum value (inclusive)
1392
+ * @param max - Maximum value (inclusive)
1393
+ * @returns A random integer between min and max
1394
+ */
1395
+ function randomIntegerInInterval(min, max) {
1396
+ return Math.floor(Math.random() * (max - min + 1) + min);
1397
+ }
1398
+ /**
1399
+ * Returns a random decimal in the range [min, max).
1400
+ * @param min - Minimum value (inclusive)
1401
+ * @param max - Maximum value (exclusive)
1402
+ * @returns A random decimal between min and max
1403
+ */
1404
+ function randomDecimalInInterval(min, max) {
1405
+ return Math.random() * (max - min) + min;
1406
+ }
1407
+ const randomId = (length) => {
1408
+ const characters = 'abcdefghijklmnopqrstuvwxyz0123456789';
1409
+ let result = '';
1410
+ for (let i = 0; i < length; i++) {
1411
+ result += characters.charAt(randomIntegerInInterval(0, characters.length - 1));
1412
+ }
1413
+ return result;
1414
+ };
1415
+ function randomPick(arr) {
1416
+ return first$1(randomPicks(arr, 1));
1417
+ }
1418
+ function randomPicks(arr, count) {
1419
+ const available = [...arr];
1420
+ const result = [];
1421
+ while (available.length > 0 && count > 0) {
1422
+ const randomIndex = randomIntegerInInterval(0, available.length - 1);
1423
+ result.push(available[randomIndex]);
1424
+ available.splice(randomIndex, 1);
1425
+ count--;
1426
+ }
1427
+ return result;
1428
+ }
1429
+
1430
+ function dictToEntries(obj) {
1431
+ return Object.entries(obj);
1432
+ }
1433
+ function entriesToDict(entries) {
1434
+ return Object.fromEntries(entries);
1435
+ }
1436
+ function entriesToEntries(dict, mapper) {
1437
+ return entriesToDict(dictToEntries(dict).map((entry) => mapper(entry)));
1438
+ }
1439
+ /** @deprecated[2025.08.01]: Compatibility layer. */
1440
+ const mapEntries = entriesToEntries;
1441
+ function entriesToList(dict, mapper) {
1442
+ return dictToEntries(dict).map((entry) => mapper(entry));
1443
+ }
1444
+
1445
+ function dictToList(obj) {
1446
+ return Object.keys(obj).map(key => obj[key]);
1447
+ }
1448
+ function pick(o, keys) {
1449
+ return keys.reduce((obj, key) => {
1450
+ obj[key] = o[key];
1451
+ return obj;
1452
+ }, {});
1453
+ }
1454
+ function shallowRecordEquals(a, b) {
1455
+ if (a === b)
1456
+ return true;
1457
+ const aKeys = Object.keys(a), bKeys = Object.keys(b);
1458
+ if (aKeys.length !== bKeys.length)
1459
+ return false;
1460
+ for (const key of aKeys) {
1461
+ if (a[key] !== b[key])
1462
+ return false;
1463
+ }
1464
+ return true;
1465
+ }
1466
+
1400
1467
  /**
1401
1468
  * Class that stores a value that is computationally/memory intensive to initialize.
1402
1469
  * The initialization of the value is done once and only if required (lazy initialization).
@@ -3669,5 +3736,5 @@ function isUpgradable(obj) {
3669
3736
  return isDefined(obj) && typeof obj === "object" && VERSION_FIELD in obj && isNumber(obj.$version) && isPositiveNumber(obj.$version);
3670
3737
  }
3671
3738
 
3672
- export { Cached, DataUpgrader, Deferred, DeferredCanceledError, ErrorCannotInstantiatePresentOptionalWithEmptyValue, ErrorGetEmptyOptional, ErrorSetEmptyOptional, Lazy, LazyAsync, LazyDictionary, Logger, NEVER, NonExhaustiveSwitchError, Operation, Optional, PredicateBuilder, RandomTimeDuration, RateThrottler, Semaphore, Sorter, StringParts, TimeDuration, TimeFrequency, TimeInstant, TimeRange, TimeUnit, TimeoutError, alwaysFalse, alwaysTrue, and, arrayGet, arrayIncludes, asError, asPromise, average, averageBy, awaitAtMost, capitalizeWord, clamp, clampInt0_100, constant, constantFalse, constantNull, constantOne, constantTrue, constantUndefined, constantZero, cssDeclarationRulesDictionaryToCss, decrement, decrementBy, delayPromise, dictToEntries, dictToList, divideBy, ellipsis, ensureArray, ensureDefined, ensureNegativeNumber, ensureNonNegativeNumber, ensureNonPositiveNumber, ensurePositiveNumber, ensureReadableArray, entriesToDict, entriesToEntries, entriesToList, extendArray, extendArrayWith, fill, fillWith, filterMap, filterMapReduce, filterWithTypePredicate, findInArray, findIndexInArray, first$1 as first, flatMapTruthys, getCauseMessageFromError, getCauseStackFromError, getMessageFromError, getStackFromError, groupByBoolean, groupByBooleanWith, groupByNumber, groupByNumberWith, groupByString, groupByStringWith, groupBySymbol, groupBySymbolWith, hashCode, havingMaxBy, havingMinBy, head, identity, ifDefined, ifNullOrUndefined, iff, includes, increment, incrementBy, indexByNumber, indexByNumberWith, indexByString, indexByStringWith, indexBySymbol, indexBySymbolWith, indexByWith, isAllowedTimeDuration, isArray, isDefined, isEmpty, isError, isFalse, isFunction, isNegativeNumber, isNullOrUndefined, isNullOrUndefinedOrEmpty, isNumber, isPositiveNumber, isString, isTimeInstant, isTrue, isUpgradable, isZero, jsonCloneDeep, last$1 as last, listToDict, mapDefined, mapEntries, mapFirstTruthy, mapTruthys, max, maxBy, min, minBy, multiplyBy, noop, not, omitFromJsonObject, or, pad, padLeft, padRight, parseJson, parseTimeInstantBasicComponents, parseTimeInstantComponents, partition, pick, pipedInvoke, pipedInvokeFromArray, pluralize, promiseSequence, randomDecimalInInterval, randomId, randomIntegerInInterval, randomNumberInInterval, randomPick, randomPicks, range, repeat, reverse$1 as reverse, round, roundAwayFromZero, roundToLower, roundToNearest, roundToUpper, roundTowardsZero, shallowArrayEquals, shallowRecordEquals, sortedArray, splitWords, stringToNumber, stringifyJson, sum, sumBy, tail, throttle, throwIfNullOrUndefined, transformCssDictionary, tryToParseJson, tryToParseNumber, uniq, uniqBy, uniqByKey, unzip, upsert, withTryCatch, withTryCatchAsync, wrapWithString, xor, zip };
3739
+ export { Cached, DataUpgrader, Deferred, DeferredCanceledError, ErrorCannotInstantiatePresentOptionalWithEmptyValue, ErrorGetEmptyOptional, ErrorSetEmptyOptional, Lazy, LazyAsync, LazyDictionary, Logger, NEVER, NonExhaustiveSwitchError, Operation, OperationAggregateError, Optional, PredicateBuilder, RandomTimeDuration, RateThrottler, Semaphore, Sorter, StringParts, TimeDuration, TimeFrequency, TimeInstant, TimeRange, TimeUnit, TimeoutError, alwaysFalse, alwaysTrue, and, arrayGet, arrayIncludes, asError, asPromise, average, averageBy, awaitAtMost, capitalizeWord, clamp, clampInt0_100, constant, constantFalse, constantNull, constantOne, constantTrue, constantUndefined, constantZero, cssDeclarationRulesDictionaryToCss, decrement, decrementBy, delayPromise, dictToEntries, dictToList, divideBy, ellipsis, ensureArray, ensureDefined, ensureNegativeNumber, ensureNonNegativeNumber, ensureNonPositiveNumber, ensurePositiveNumber, ensureReadableArray, entriesToDict, entriesToEntries, entriesToList, extendArray, extendArrayWith, fill, fillWith, filterMap, filterMapReduce, filterWithTypePredicate, findInArray, findIndexInArray, first$1 as first, flatMapTruthys, getCauseMessageFromError, getCauseStackFromError, getMessageFromError, getStackFromError, groupByBoolean, groupByBooleanWith, groupByNumber, groupByNumberWith, groupByString, groupByStringWith, groupBySymbol, groupBySymbolWith, hashCode, havingMaxBy, havingMinBy, head, identity, ifDefined, ifNullOrUndefined, iff, includes, increment, incrementBy, indexByNumber, indexByNumberWith, indexByString, indexByStringWith, indexBySymbol, indexBySymbolWith, indexByWith, isAllowedTimeDuration, isArray, isDefined, isEmpty, isError, isFalse, isFunction, isNegativeNumber, isNullOrUndefined, isNullOrUndefinedOrEmpty, isNumber, isPositiveNumber, isString, isTimeInstant, isTrue, isUpgradable, isZero, jsonCloneDeep, last$1 as last, listToDict, mapDefined, mapEntries, mapFirstTruthy, mapTruthys, max, maxBy, min, minBy, multiplyBy, noop, not, omitFromJsonObject, or, pad, padLeft, padRight, parseJson, parseTimeInstantBasicComponents, parseTimeInstantComponents, partition, pick, pipedInvoke, pipedInvokeFromArray, pluralize, promiseSequence, randomDecimalInInterval, randomId, randomIntegerInInterval, randomNumberInInterval, randomPick, randomPicks, range, repeat, reverse$1 as reverse, round, roundAwayFromZero, roundToLower, roundToNearest, roundToUpper, roundTowardsZero, shallowArrayEquals, shallowRecordEquals, sortedArray, splitWords, stringToNumber, stringifyJson, sum, sumBy, tail, throttle, throwIfNullOrUndefined, transformCssDictionary, tryToParseJson, tryToParseNumber, uniq, uniqBy, uniqByKey, unzip, upsert, withTryCatch, withTryCatchAsync, wrapWithString, xor, zip };
3673
3740
  //# sourceMappingURL=index.mjs.map