@oscarpalmer/atoms 0.199.0 → 0.201.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.mjs CHANGED
@@ -68,12 +68,16 @@ function findValues(type, array, parameters, mapper) {
68
68
  result.matched = [...new Set(array)];
69
69
  return result;
70
70
  }
71
- const mapCallback = getArrayCallback(mapper);
71
+ const mapCallback = getArrayCallback(mapper?.callback);
72
+ const mapReverse = mapper?.reverse ?? false;
73
+ const mapAfter = mapCallback == null ? void 0 : mapReverse ? void 0 : mapCallback;
74
+ const mapBefore = mapCallback == null ? void 0 : mapReverse ? mapCallback : void 0;
72
75
  if (callbacks?.bool != null || type === "all" && key == null) {
73
76
  const callback = callbacks?.bool ?? ((item) => Object.is(item, value));
74
77
  for (let index = 0; index < length; index += 1) {
75
78
  const item = array[index];
76
- if (callback(item, index, array)) result.matched.push(mapCallback?.(item, index, array) ?? item);
79
+ const transformed = mapBefore?.(item, index, array) ?? item;
80
+ if (callback(transformed, index, array)) result.matched.push(mapAfter?.(item, index, array) ?? transformed);
77
81
  else result.notMatched.push(item);
78
82
  }
79
83
  return result;
@@ -81,10 +85,18 @@ function findValues(type, array, parameters, mapper) {
81
85
  const keys = /* @__PURE__ */ new Set();
82
86
  for (let index = 0; index < length; index += 1) {
83
87
  const item = array[index];
84
- const keyed = callbacks?.keyed?.(item, index, array) ?? item;
88
+ let keyed;
89
+ let transformed;
90
+ if (mapBefore == null) {
91
+ keyed = callbacks?.keyed?.(item, index, array) ?? item;
92
+ transformed = item;
93
+ } else {
94
+ transformed = mapBefore(item, index, array);
95
+ keyed = callbacks?.keyed?.(transformed, index, array) ?? transformed;
96
+ }
85
97
  if (type === "all" && Object.is(keyed, value) || type === "unique" && !keys.has(keyed)) {
86
98
  keys.add(keyed);
87
- result.matched.push(mapCallback?.(item, index, array) ?? item);
99
+ result.matched.push(mapAfter?.(item, index, array) ?? transformed);
88
100
  } else result.notMatched.push(item);
89
101
  }
90
102
  return result;
@@ -661,9 +673,23 @@ function reverse(array) {
661
673
  }
662
674
  //#endregion
663
675
  //#region src/array/select.ts
676
+ function reverseSelect(array, ...parameters) {
677
+ return findValues("all", array, parameters, {
678
+ callback: parameters.shift(),
679
+ reverse: true
680
+ }).matched;
681
+ }
664
682
  function select(array, ...parameters) {
665
- return findValues("all", array, parameters, parameters.pop()).matched;
683
+ return selectValues(array, parameters);
666
684
  }
685
+ function selectValues(array, parameters) {
686
+ return findValues("all", array, parameters, {
687
+ callback: parameters.pop(),
688
+ reverse: false
689
+ }).matched;
690
+ }
691
+ select.reverse = reverseSelect;
692
+ Object.defineProperty(select, "reverse", { value: reverseSelect });
667
693
  //#endregion
668
694
  //#region src/array/single.ts
669
695
  function single(array, ...parameters) {
@@ -2597,6 +2623,8 @@ const ABORT_OPTIONS = { once: true };
2597
2623
  //#region src/promise/constants.ts
2598
2624
  const PROMISE_ERROR_NAME = "PromiseTimeoutError";
2599
2625
  const PROMISE_MESSAGE_EXPECTATION_ATTEMPT = "Attempt expected a function or a promise";
2626
+ const PROMISE_MESSAGE_EXPECTATION_ITEMS_EMPTY = "promises expected at least one promise-function or promise in the array or object";
2627
+ const PROMISE_MESSAGE_EXPECTATION_ITEMS_TYPE = "promises expected an array or object holding promise-functions or promises";
2600
2628
  const PROMISE_MESSAGE_EXPECTATION_RESULT = "toResult expected a Promise";
2601
2629
  const PROMISE_MESSAGE_EXPECTATION_TIMED = "Timed function expected a Promise";
2602
2630
  const PROMISE_MESSAGE_TIMEOUT = "Promise timed out";
@@ -2665,7 +2693,15 @@ function createPromisesOptions(input) {
2665
2693
  };
2666
2694
  }
2667
2695
  function getResultsFromPromises(promised) {
2668
- return promised.map((result) => isFulfilled(result) ? ok(result.value) : error(result.reason));
2696
+ const isArray = Array.isArray(promised);
2697
+ const entries = isArray ? promised.map((value, index) => [index, value]) : Object.entries(promised);
2698
+ const { length } = entries;
2699
+ const results = isArray ? [] : {};
2700
+ for (let index = 0; index < length; index += 1) {
2701
+ const [key, value] = entries[index];
2702
+ results[key] = isFulfilled(value) ? ok(value.value) : error(value.reason);
2703
+ }
2704
+ return results;
2669
2705
  }
2670
2706
  function getStrategyOrDefault(value) {
2671
2707
  return PROMISE_STRATEGY_ALL.has(value) ? value : PROMISE_STRATEGY_DEFAULT;
@@ -2719,13 +2755,13 @@ function cancelable(executor) {
2719
2755
  return new CancelablePromise(executor);
2720
2756
  }
2721
2757
  function handleResult(status, parameters) {
2722
- const { aborter, complete, data, handlers, index, value } = parameters;
2758
+ const { aborter, complete, data, handlers, index, key, value } = parameters;
2723
2759
  if (aborter?.signal.aborted ?? false) return;
2724
2760
  if (!complete && status === "rejected") {
2725
2761
  settlePromise(handlers.reject, value, aborter);
2726
2762
  return;
2727
2763
  }
2728
- data.result[index] = !complete ? value : status === "fulfilled" ? {
2764
+ data.result[key] = !complete ? value : status === "fulfilled" ? {
2729
2765
  status,
2730
2766
  value
2731
2767
  } : {
@@ -2816,17 +2852,18 @@ async function attemptPromise(value, options) {
2816
2852
  async function promises(items, options) {
2817
2853
  const { signal, strategy } = createPromisesOptions(options);
2818
2854
  if (signal?.aborted ?? false) return Promise.reject(signal?.reason);
2819
- if (!Array.isArray(items)) return Promise.resolve([]);
2820
- const actual = items.map((item) => typeof item === "function" ? item() : item).filter((item) => item instanceof Promise);
2855
+ if (!isArrayOrPlainObject(items)) return Promise.reject(PROMISE_MESSAGE_EXPECTATION_ITEMS_TYPE);
2856
+ const isArray = Array.isArray(items);
2857
+ const actual = (isArray ? items.map((item, index) => [index, item]) : Object.entries(items)).map(([key, value]) => [key, typeof value === "function" ? value() : value]).filter(([, value]) => value instanceof Promise);
2821
2858
  const { length } = actual;
2822
- if (length === 0) return Promise.resolve([]);
2859
+ if (length === 0) return Promise.reject(PROMISE_MESSAGE_EXPECTATION_ITEMS_EMPTY);
2823
2860
  const complete = strategy === PROMISE_STRATEGY_DEFAULT;
2824
2861
  const aborter = createAborter(signal, () => {
2825
2862
  handlers.reject(signal?.reason);
2826
2863
  });
2827
2864
  const data = {
2828
2865
  last: length - 1,
2829
- result: []
2866
+ result: isArray ? [] : {}
2830
2867
  };
2831
2868
  let handlers;
2832
2869
  return new Promise((resolve, reject) => {
@@ -2834,21 +2871,24 @@ async function promises(items, options) {
2834
2871
  reject,
2835
2872
  resolve
2836
2873
  };
2837
- for (let index = 0; index < length; index += 1) actual[index].then((value) => handleResult(PROMISE_TYPE_FULFILLED, {
2838
- aborter,
2839
- complete,
2840
- data,
2841
- handlers,
2842
- index,
2843
- value
2844
- })).catch((reason) => handleResult(PROMISE_TYPE_REJECTED, {
2845
- aborter,
2846
- complete,
2847
- data,
2848
- handlers,
2849
- index,
2850
- value: reason
2851
- }));
2874
+ for (let index = 0; index < length; index += 1) {
2875
+ const [key, promise] = actual[index];
2876
+ const parameters = {
2877
+ aborter,
2878
+ complete,
2879
+ data,
2880
+ handlers,
2881
+ index,
2882
+ key
2883
+ };
2884
+ promise.then((value) => {
2885
+ parameters.value = value;
2886
+ handleResult(PROMISE_TYPE_FULFILLED, parameters);
2887
+ }).catch((reason) => {
2888
+ parameters.value = reason;
2889
+ handleResult(PROMISE_TYPE_REJECTED, parameters);
2890
+ });
2891
+ }
2852
2892
  });
2853
2893
  }
2854
2894
  async function resultPromises(items, signal) {
@@ -3050,6 +3090,8 @@ function fuzzy(items, configuration) {
3050
3090
  }
3051
3091
  /**
3052
3092
  * Does the needle match the haystack in a fuzzy way?
3093
+ *
3094
+ * _Available as `fuzzyMatch` and `fuzzy.match`_
3053
3095
  *
3054
3096
  * @param haystack Haystack to search through
3055
3097
  * @param needle Needle to search for
@@ -3792,6 +3834,8 @@ function freezeValue(value, references, flat) {
3792
3834
  }
3793
3835
  /**
3794
3836
  * Is the value frozen?
3837
+ *
3838
+ * _Available as `isFrozen` and `freeze.is`_
3795
3839
  *
3796
3840
  * @param value Value to check
3797
3841
  * @returns `true` if the value is frozen, otherwise `false`
@@ -3968,7 +4012,8 @@ function createMergeOptions(options) {
3968
4012
  }
3969
4013
  function getReplaceableObjects(value) {
3970
4014
  const items = (Array.isArray(value) ? value : [value]).filter((item) => typeof item === "string" || item instanceof RegExp);
3971
- if (items.length > 0) return (name) => items.some((item) => typeof item === "string" ? item === name : item.test(name));
4015
+ if (items.length === 0) return;
4016
+ return (name) => items.some((item) => typeof item === "string" ? item === name : item.test(name));
3972
4017
  }
3973
4018
  /**
3974
4019
  * Create an assigner with predefined options
@@ -6469,4 +6514,4 @@ var SizedSet = class extends Set {
6469
6514
  }
6470
6515
  };
6471
6516
  //#endregion
6472
- export { CancelablePromise, Logger, PromiseTimeoutError, QueueError, RetryError, SORT_DIRECTION_ASCENDING, SORT_DIRECTION_DESCENDING, SizedMap, SizedSet, assert, assertCondition, assertDefined, assertInstanceOf, assertIs, assertProperty, assign, asyncAttempt, asyncDebounce, asyncFlow, asyncMatchResult, asyncOnce, asyncPipe, asyncThrottle, attempt, attemptAsyncFlow, attemptAsyncPipe, attemptFlow, attemptPipe, attemptPromise, average, beacon, between, camelCase, cancelable, capitalize, ceil, chunk, clamp, clone, compact, compare, copy, count, debounce, deburr, dedent, delay, deregisterCloner, deregisterComparator, deregisterEqualizer, diff, difference, drop, endsWith, endsWithArray, equal, error, exclude, exists, filter, find, findLast, first, firstOrDefault, flatFreeze, flatten, floor, flow, freeze, fromQuery, toPromise as fromResult, toPromise, fuzzy, fuzzyMatch, getArray, getArrayComparison, getColor, getForegroundColor, getHexColor, getHexaColor, getHslColor, getHslaColor, getHwbColor, getHwbaColor, getNormalizedHex, getNumber, getRandomBoolean, getRandomCharacters, getRandomColor, getRandomFloatingNumber as getRandomFloat, getRandomHex, getRandomInteger, getRandomItem, getRandomItems, getRgbColor, getRgbaColor, getSortedIndex, getString, getTimedPromise, getUuid, getValue, groupArraysBy, groupBy, handleResult, hasValue, hasValueResult, herald, hexToHsl, hexToHsla, hexToHwb, hexToHwba, hexToRgb, hexToRgba, hslToHex, hslToHwb, hslToHwba, hslToRgb, hslToRgba, hwbToHex, hwbToHsl, hwbToHsla, hwbToRgb, hwbToRgba, ignoreKey, inMap, inSet, includes, includesArray, indexOf, indexOfArray, initializeAssigner, initializeCloner, initializeEqualizer, initializeMerger, initializeNormalizer, initializeSorter, initializeTemplater, initializeTransformer, insert, interpolate, intersection, isArrayOrPlainObject, isBeacon, isBeaconSubscription, isColor, isConstructor, isEmpty, isError, isFrozen, isFulfilled, isHerald, isHeraldEvents, isHeraldSubscription, isHexColor, isHslColor, isHslaColor, isHwbColor, isHwbaColor, isInstanceOf, isKey, isKeyedQueue, isLogger, isNonArrayOrPlainObject, isNonConstructor, isNonEmpty, isNonInstanceOf, isNonKey, isNonNullable, isNonNullableOrEmpty, isNonNullableOrWhitespace, isNonNumber, isNonNumerical, isNonObject, isNonPlainObject, isNonPrimitive, isNonTypedArray, isNullable, isNullableOrEmpty, isNullableOrWhitespace, isNumber, isNumerical, isObject, isObservable, isOk, isPlainObject, isPrimitive, isQueue, isQueueInstance, isRejected, isResult, isRgbColor, isRgbaColor, isSorted, isSubscription, isSubscriptions, isTimedLogger, isTypedArray, join, kebabCase, keyedQueue, last, lastIndexOf, lastOrDefault, lowerCase, matchResult, max, median, memoize, merge, min, move, moveIndices, moveToIndex, noop, normalize, ok, omit, once, parse, partition, pascalCase, pick, pipe, promises, push, queue, range, registerCloner, registerComparator, registerEqualizer, resultPromises, retry, reverse, rgbToHex, rgbToHsl, rgbToHsla, rgbToHwb, rgbToHwba, round, select, setValue, settlePromise, shake, shuffle, single, slice, smush, snakeCase, sort, splice, startsWith, startsWithArray, subscriptions, sum, swap, take, template, throttle, timed, times, titleCase, toMap, toMapArrays, toQuery, toRecord, toRecordArrays, toResult, toSet, toggle, transform, trim, truncate, tryDecode, tryEncode, union, unique, unsmush, unwrap, update, upperCase, words };
6517
+ export { CancelablePromise, Logger, PromiseTimeoutError, QueueError, RetryError, SORT_DIRECTION_ASCENDING, SORT_DIRECTION_DESCENDING, SizedMap, SizedSet, assert, assertCondition, assertDefined, assertInstanceOf, assertIs, assertProperty, assign, asyncAttempt, asyncDebounce, asyncFlow, asyncMatchResult, asyncOnce, asyncPipe, asyncThrottle, attempt, attemptAsyncFlow, attemptAsyncPipe, attemptFlow, attemptPipe, attemptPromise, average, beacon, between, camelCase, cancelable, capitalize, ceil, chunk, clamp, clone, compact, compare, copy, count, debounce, deburr, dedent, delay, deregisterCloner, deregisterComparator, deregisterEqualizer, diff, difference, drop, endsWith, endsWithArray, equal, error, exclude, exists, filter, find, findLast, first, firstOrDefault, flatFreeze, flatten, floor, flow, freeze, fromQuery, toPromise as fromResult, toPromise, fuzzy, fuzzyMatch, getArray, getArrayComparison, getColor, getForegroundColor, getHexColor, getHexaColor, getHslColor, getHslaColor, getHwbColor, getHwbaColor, getNormalizedHex, getNumber, getRandomBoolean, getRandomCharacters, getRandomColor, getRandomFloatingNumber as getRandomFloat, getRandomHex, getRandomInteger, getRandomItem, getRandomItems, getRgbColor, getRgbaColor, getSortedIndex, getString, getTimedPromise, getUuid, getValue, groupArraysBy, groupBy, handleResult, hasValue, hasValueResult, herald, hexToHsl, hexToHsla, hexToHwb, hexToHwba, hexToRgb, hexToRgba, hslToHex, hslToHwb, hslToHwba, hslToRgb, hslToRgba, hwbToHex, hwbToHsl, hwbToHsla, hwbToRgb, hwbToRgba, ignoreKey, inMap, inSet, includes, includesArray, indexOf, indexOfArray, initializeAssigner, initializeCloner, initializeEqualizer, initializeMerger, initializeNormalizer, initializeSorter, initializeTemplater, initializeTransformer, insert, interpolate, intersection, isArrayOrPlainObject, isBeacon, isBeaconSubscription, isColor, isConstructor, isEmpty, isError, isFrozen, isFulfilled, isHerald, isHeraldEvents, isHeraldSubscription, isHexColor, isHslColor, isHslaColor, isHwbColor, isHwbaColor, isInstanceOf, isKey, isKeyedQueue, isLogger, isNonArrayOrPlainObject, isNonConstructor, isNonEmpty, isNonInstanceOf, isNonKey, isNonNullable, isNonNullableOrEmpty, isNonNullableOrWhitespace, isNonNumber, isNonNumerical, isNonObject, isNonPlainObject, isNonPrimitive, isNonTypedArray, isNullable, isNullableOrEmpty, isNullableOrWhitespace, isNumber, isNumerical, isObject, isObservable, isOk, isPlainObject, isPrimitive, isQueue, isQueueInstance, isRejected, isResult, isRgbColor, isRgbaColor, isSorted, isSubscription, isSubscriptions, isTimedLogger, isTypedArray, join, kebabCase, keyedQueue, last, lastIndexOf, lastOrDefault, lowerCase, matchResult, max, median, memoize, merge, min, move, moveIndices, moveToIndex, noop, normalize, ok, omit, once, parse, partition, pascalCase, pick, pipe, promises, push, queue, range, registerCloner, registerComparator, registerEqualizer, resultPromises, retry, reverse, reverseSelect, rgbToHex, rgbToHsl, rgbToHsla, rgbToHwb, rgbToHwba, round, select, setValue, settlePromise, shake, shuffle, single, slice, smush, snakeCase, sort, splice, startsWith, startsWithArray, subscriptions, sum, swap, take, template, throttle, timed, times, titleCase, toMap, toMapArrays, toQuery, toRecord, toRecordArrays, toResult, toSet, toggle, transform, trim, truncate, tryDecode, tryEncode, union, unique, unsmush, unwrap, update, upperCase, words };
@@ -11,7 +11,7 @@
11
11
  * compact([0, 1, '', 'hello', false, true, null, undefined]); // => [1, 'hello', true]
12
12
  * ```
13
13
  */
14
- declare function compact<Item>(array: Item[], strict: true): Exclude<Item, 0 | '' | false | null | undefined>[];
14
+ declare function compact<Item>(array: Item[], strict: true): Array<Exclude<Item, 0 | '' | false | null | undefined>>;
15
15
  /**
16
16
  * Compact an array _(removing all `null` and `undefined` values)_
17
17
  *
@@ -23,6 +23,6 @@ declare function compact<Item>(array: Item[], strict: true): Exclude<Item, 0 | '
23
23
  * compact([0, 1, '', 'hello', false, true, null, undefined]); // => [0, 1, '', 'hello', false, true]
24
24
  * ```
25
25
  */
26
- declare function compact<Item>(array: Item[]): Exclude<Item, null | undefined>[];
26
+ declare function compact<Item>(array: Item[]): Array<Exclude<Item, null | undefined>>;
27
27
  //#endregion
28
28
  export { compact };
@@ -1,4 +1,8 @@
1
1
  //#region src/internal/array/find.d.ts
2
+ type FindMapper = {
3
+ callback: unknown;
4
+ reverse: boolean;
5
+ };
2
6
  type FindValueType = 'index' | 'item';
3
7
  type FindValuesResult = {
4
8
  matched: unknown[];
@@ -14,7 +18,7 @@ declare function createFindParameters(original: unknown[]): Parameters;
14
18
  declare function findValue(type: Exclude<FindValueType, 'item'>, array: unknown[], parameters: unknown[], reversed: boolean): number;
15
19
  declare function findValue(type: Exclude<FindValueType, 'index'>, array: unknown[], parameters: unknown[], reversed: boolean): unknown;
16
20
  declare function findAbsoluteValueOrDefault(array: unknown[], parameters: unknown[], defaultValue: unknown, useDefaultValue: boolean, reversed: boolean): unknown;
17
- declare function findValues(type: FindValuesType, array: unknown[], parameters: unknown[], mapper?: unknown): FindValuesResult;
21
+ declare function findValues(type: FindValuesType, array: unknown[], parameters: unknown[], mapper?: FindMapper): FindValuesResult;
18
22
  declare const FIND_VALUE_INDEX = "index";
19
23
  declare const FIND_VALUE_ITEM = "item";
20
24
  declare const FIND_VALUES_ALL: FindValuesType;
@@ -52,12 +52,16 @@ function findValues(type, array, parameters, mapper) {
52
52
  result.matched = [...new Set(array)];
53
53
  return result;
54
54
  }
55
- const mapCallback = getArrayCallback(mapper);
55
+ const mapCallback = getArrayCallback(mapper?.callback);
56
+ const mapReverse = mapper?.reverse ?? false;
57
+ const mapAfter = mapCallback == null ? void 0 : mapReverse ? void 0 : mapCallback;
58
+ const mapBefore = mapCallback == null ? void 0 : mapReverse ? mapCallback : void 0;
56
59
  if (callbacks?.bool != null || type === "all" && key == null) {
57
60
  const callback = callbacks?.bool ?? ((item) => Object.is(item, value));
58
61
  for (let index = 0; index < length; index += 1) {
59
62
  const item = array[index];
60
- if (callback(item, index, array)) result.matched.push(mapCallback?.(item, index, array) ?? item);
63
+ const transformed = mapBefore?.(item, index, array) ?? item;
64
+ if (callback(transformed, index, array)) result.matched.push(mapAfter?.(item, index, array) ?? transformed);
61
65
  else result.notMatched.push(item);
62
66
  }
63
67
  return result;
@@ -65,10 +69,18 @@ function findValues(type, array, parameters, mapper) {
65
69
  const keys = /* @__PURE__ */ new Set();
66
70
  for (let index = 0; index < length; index += 1) {
67
71
  const item = array[index];
68
- const keyed = callbacks?.keyed?.(item, index, array) ?? item;
72
+ let keyed;
73
+ let transformed;
74
+ if (mapBefore == null) {
75
+ keyed = callbacks?.keyed?.(item, index, array) ?? item;
76
+ transformed = item;
77
+ } else {
78
+ transformed = mapBefore(item, index, array);
79
+ keyed = callbacks?.keyed?.(transformed, index, array) ?? transformed;
80
+ }
69
81
  if (type === "all" && Object.is(keyed, value) || type === "unique" && !keys.has(keyed)) {
70
82
  keys.add(keyed);
71
- result.matched.push(mapCallback?.(item, index, array) ?? item);
83
+ result.matched.push(mapAfter?.(item, index, array) ?? transformed);
72
84
  } else result.notMatched.push(item);
73
85
  }
74
86
  return result;
@@ -6,6 +6,8 @@ declare const PROMISE_ABORT_OPTIONS: {
6
6
  };
7
7
  declare const PROMISE_ERROR_NAME = "PromiseTimeoutError";
8
8
  declare const PROMISE_MESSAGE_EXPECTATION_ATTEMPT = "Attempt expected a function or a promise";
9
+ declare const PROMISE_MESSAGE_EXPECTATION_ITEMS_EMPTY = "promises expected at least one promise-function or promise in the array or object";
10
+ declare const PROMISE_MESSAGE_EXPECTATION_ITEMS_TYPE = "promises expected an array or object holding promise-functions or promises";
9
11
  declare const PROMISE_MESSAGE_EXPECTATION_RESULT = "toResult expected a Promise";
10
12
  declare const PROMISE_MESSAGE_EXPECTATION_TIMED = "Timed function expected a Promise";
11
13
  declare const PROMISE_MESSAGE_TIMEOUT = "Promise timed out";
@@ -14,4 +16,4 @@ declare const PROMISE_STRATEGY_DEFAULT: PromiseStrategy;
14
16
  declare const PROMISE_TYPE_FULFILLED = "fulfilled";
15
17
  declare const PROMISE_TYPE_REJECTED = "rejected";
16
18
  //#endregion
17
- export { PROMISE_ABORT_EVENT, PROMISE_ABORT_OPTIONS, PROMISE_ERROR_NAME, PROMISE_MESSAGE_EXPECTATION_ATTEMPT, PROMISE_MESSAGE_EXPECTATION_RESULT, PROMISE_MESSAGE_EXPECTATION_TIMED, PROMISE_MESSAGE_TIMEOUT, PROMISE_STRATEGY_ALL, PROMISE_STRATEGY_DEFAULT, PROMISE_TYPE_FULFILLED, PROMISE_TYPE_REJECTED };
19
+ export { PROMISE_ABORT_EVENT, PROMISE_ABORT_OPTIONS, PROMISE_ERROR_NAME, PROMISE_MESSAGE_EXPECTATION_ATTEMPT, PROMISE_MESSAGE_EXPECTATION_ITEMS_EMPTY, PROMISE_MESSAGE_EXPECTATION_ITEMS_TYPE, PROMISE_MESSAGE_EXPECTATION_RESULT, PROMISE_MESSAGE_EXPECTATION_TIMED, PROMISE_MESSAGE_TIMEOUT, PROMISE_STRATEGY_ALL, PROMISE_STRATEGY_DEFAULT, PROMISE_TYPE_FULFILLED, PROMISE_TYPE_REJECTED };
@@ -3,6 +3,8 @@ const PROMISE_ABORT_EVENT = "abort";
3
3
  const PROMISE_ABORT_OPTIONS = { once: true };
4
4
  const PROMISE_ERROR_NAME = "PromiseTimeoutError";
5
5
  const PROMISE_MESSAGE_EXPECTATION_ATTEMPT = "Attempt expected a function or a promise";
6
+ const PROMISE_MESSAGE_EXPECTATION_ITEMS_EMPTY = "promises expected at least one promise-function or promise in the array or object";
7
+ const PROMISE_MESSAGE_EXPECTATION_ITEMS_TYPE = "promises expected an array or object holding promise-functions or promises";
6
8
  const PROMISE_MESSAGE_EXPECTATION_RESULT = "toResult expected a Promise";
7
9
  const PROMISE_MESSAGE_EXPECTATION_TIMED = "Timed function expected a Promise";
8
10
  const PROMISE_MESSAGE_TIMEOUT = "Promise timed out";
@@ -11,4 +13,4 @@ const PROMISE_STRATEGY_DEFAULT = "complete";
11
13
  const PROMISE_TYPE_FULFILLED = "fulfilled";
12
14
  const PROMISE_TYPE_REJECTED = "rejected";
13
15
  //#endregion
14
- export { PROMISE_ABORT_EVENT, PROMISE_ABORT_OPTIONS, PROMISE_ERROR_NAME, PROMISE_MESSAGE_EXPECTATION_ATTEMPT, PROMISE_MESSAGE_EXPECTATION_RESULT, PROMISE_MESSAGE_EXPECTATION_TIMED, PROMISE_MESSAGE_TIMEOUT, PROMISE_STRATEGY_ALL, PROMISE_STRATEGY_DEFAULT, PROMISE_TYPE_FULFILLED, PROMISE_TYPE_REJECTED };
16
+ export { PROMISE_ABORT_EVENT, PROMISE_ABORT_OPTIONS, PROMISE_ERROR_NAME, PROMISE_MESSAGE_EXPECTATION_ATTEMPT, PROMISE_MESSAGE_EXPECTATION_ITEMS_EMPTY, PROMISE_MESSAGE_EXPECTATION_ITEMS_TYPE, PROMISE_MESSAGE_EXPECTATION_RESULT, PROMISE_MESSAGE_EXPECTATION_TIMED, PROMISE_MESSAGE_TIMEOUT, PROMISE_STRATEGY_ALL, PROMISE_STRATEGY_DEFAULT, PROMISE_TYPE_FULFILLED, PROMISE_TYPE_REJECTED };
@@ -1,10 +1,9 @@
1
1
  import { RequiredKeys } from "../models.mjs";
2
- import { Result } from "../internal/result/models.mjs";
3
2
  import { FulfilledPromise, PromiseOptions, PromiseStrategy, PromisesOptions, PromisesValue, RejectedPromise } from "./models.mjs";
4
3
  //#region src/promise/helpers.d.ts
5
4
  declare function createPromiseOptions(input: unknown): RequiredKeys<PromiseOptions, 'time'>;
6
5
  declare function createPromisesOptions(input: unknown): RequiredKeys<PromisesOptions, 'strategy'>;
7
- declare function getResultsFromPromises<Value>(promised: PromisesValue<Value>[]): Result<Value>[];
6
+ declare function getResultsFromPromises(promised: Array<PromisesValue<unknown>> | Record<string, PromisesValue<unknown>>): unknown;
8
7
  declare function getStrategyOrDefault(value: unknown): PromiseStrategy;
9
8
  /**
10
9
  * Is the value a fulfilled _Promise_ result?
@@ -27,7 +27,15 @@ function createPromisesOptions(input) {
27
27
  };
28
28
  }
29
29
  function getResultsFromPromises(promised) {
30
- return promised.map((result) => isFulfilled(result) ? ok(result.value) : error(result.reason));
30
+ const isArray = Array.isArray(promised);
31
+ const entries = isArray ? promised.map((value, index) => [index, value]) : Object.entries(promised);
32
+ const { length } = entries;
33
+ const results = isArray ? [] : {};
34
+ for (let index = 0; index < length; index += 1) {
35
+ const [key, value] = entries[index];
36
+ results[key] = isFulfilled(value) ? ok(value.value) : error(value.reason);
37
+ }
38
+ return results;
31
39
  }
32
40
  function getStrategyOrDefault(value) {
33
41
  return PROMISE_STRATEGY_ALL.has(value) ? value : PROMISE_STRATEGY_DEFAULT;
@@ -1,8 +1,8 @@
1
- import { Result } from "../internal/result/models.mjs";
2
- import { PromiseOptions, PromisesItems, PromisesOptions, PromisesResult, PromisesUnwrapped, PromisesValue, PromisesValues } from "./models.mjs";
1
+ import { PlainObject } from "../models.mjs";
2
+ import { PromiseOptions, PromiseStrategy, PromisesItems, PromisesOptions, PromisesResult, PromisesUnwrapped, PromisesValues } from "./models.mjs";
3
3
  //#region src/promise/index.d.ts
4
4
  /**
5
- * Wrap a _Promise_ with safety handlers, with optional abort capabilities and timeout
5
+ * Wrap a _Promise_ with safety handlers
6
6
  *
7
7
  * @param promise _Promise_ to wrap
8
8
  * @param options Options for the _Promise_
@@ -10,7 +10,7 @@ import { PromiseOptions, PromisesItems, PromisesOptions, PromisesResult, Promise
10
10
  */
11
11
  declare function attemptPromise<Value>(promise: Promise<Value>, options?: PromiseOptions | AbortSignal | number): Promise<Value>;
12
12
  /**
13
- * Wrap a _Promise_-returning callback with safety handlers, with optional abort capabilities and timeout
13
+ * Wrap a _Promise_-returning callback with safety handlers
14
14
  *
15
15
  * @param callback Callback to wrap
16
16
  * @param options Options for the _Promise_
@@ -18,7 +18,7 @@ declare function attemptPromise<Value>(promise: Promise<Value>, options?: Promis
18
18
  */
19
19
  declare function attemptPromise<Value>(callback: () => Promise<Value>, options?: PromiseOptions | AbortSignal | number): Promise<Value>;
20
20
  /**
21
- * Wrap a callback with a _Promise_ and safety handlers, with optional abort capabilities and timeout
21
+ * Wrap a callback with a _Promise_ and safety handlers
22
22
  *
23
23
  * @param callback Callback to wrap
24
24
  * @param options Options for the _Promise_
@@ -28,7 +28,7 @@ declare function attemptPromise<Value>(callback: () => Value, options?: PromiseO
28
28
  /**
29
29
  * Handle a list of _Promises_, returning their results in an ordered array
30
30
  *
31
- * Depending on the strategy, the function will either reject on the first error encountered or return an array of rejected and resolved results
31
+ * _Depending on the strategy, the function will either reject on the first error encountered or return an array of rejected and resolved results_
32
32
  *
33
33
  * @param items List of _Promises_
34
34
  * @param options Options for handling the _Promises_
@@ -36,77 +36,75 @@ declare function attemptPromise<Value>(callback: () => Value, options?: PromiseO
36
36
  */
37
37
  declare function promises<Items extends unknown[], Options extends PromisesOptions>(items: [...Items], options?: Options): Promise<Options['strategy'] extends 'first' ? PromisesUnwrapped<Items> : PromisesValues<PromisesItems<Items>>>;
38
38
  /**
39
- * Handle a list of _Promises_, returning their results in an ordered array
39
+ * Handle keyed _Promises_, returning their results in a similarly keyed object
40
40
  *
41
- * Depending on the strategy, the function will either reject on the first error encountered or return an array of rejected and resolved results
41
+ * _Depending on the strategy, the function will either reject on the first error encountered or return an object of rejected and resolved results_
42
42
  *
43
- * @param items List of _Promises_
43
+ * @param items Keyed _Promises_
44
44
  * @param options Options for handling the _Promises_
45
- * @returns List of results
45
+ * @returns Keyed object of results
46
46
  */
47
- declare function promises<Value, Options extends PromisesOptions>(items: Promise<Value>[], options?: Options): Promise<Options['strategy'] extends 'first' ? Value[] : PromisesValue<Value>[]>;
47
+ declare function promises<Items extends PlainObject, Options extends PromisesOptions>(items: Items, options?: Options): Promise<Options['strategy'] extends 'first' ? PromisesUnwrapped<Items> : PromisesValues<PromisesItems<Items>>>;
48
48
  /**
49
49
  * Handle a list of _Promises_, returning their results in an ordered array
50
50
  *
51
- * If any _Promise_ in the list is rejected, the whole function will reject
51
+ * _If the strategy is `first`, the function will reject on the first error encountered; otherwise, it returns an array of rejected and resolved results_
52
52
  *
53
53
  * @param items List of _Promises_
54
- * @param strategy Strategy for handling the _Promises_; rejects on the first error encountered
54
+ * @param strategy Strategy for handling the _Promises_
55
55
  * @returns List of results
56
56
  */
57
- declare function promises<Items extends unknown[]>(items: [...Items], strategy: 'first'): Promise<PromisesUnwrapped<Items>>;
57
+ declare function promises<Items extends unknown[], Strategy extends PromiseStrategy>(items: [...Items], strategy: Strategy): Promise<Strategy extends 'first' ? PromisesUnwrapped<Items> : PromisesValues<PromisesItems<Items>>>;
58
58
  /**
59
- * Handle a list of _Promises_, returning their results in an ordered array
59
+ * Handle keyed _Promises_, returning their results in a similarly keyed object
60
60
  *
61
- * If any _Promise_ in the list is rejected, the whole function will reject
61
+ * _If the strategy is `first`, the function will reject on the first error encountered; otherwise, it returns an object of rejected and resolved results_
62
62
  *
63
- * @param items List of _Promises_
64
- * @param strategy Strategy for handling the _Promises_; rejects on the first error encountered
65
- * @returns List of results
63
+ * @param items Keyed _Promises_
64
+ * @param strategy Strategy for handling the _Promises_
65
+ * @returns Keyed object of results
66
66
  */
67
- declare function promises<Value>(items: Promise<Value>[], strategy: 'first'): Promise<Value[]>;
67
+ declare function promises<Items extends PlainObject, Strategy extends PromiseStrategy>(items: Items, strategy: Strategy): Promise<Strategy extends 'first' ? PromisesUnwrapped<Items> : PromisesValues<PromisesItems<Items>>>;
68
68
  /**
69
- * Handle a list of _Promises_, returning their results in an ordered array of rejected and resolved results
69
+ * Handle a list of _Promises_, returning their results in an ordered array
70
70
  *
71
71
  * @param items List of _Promises_
72
- * @param signal AbortSignal for aborting the operation _(when aborted, the _Promise_ will reject with the reason of the signal)_
72
+ * @param signal _AbortSignal_ for aborting all _Promises_
73
73
  * @returns List of results
74
74
  */
75
75
  declare function promises<Items extends unknown[]>(items: [...Items], signal?: AbortSignal): Promise<PromisesValues<PromisesItems<Items>>>;
76
76
  /**
77
- * Handle a list of _Promises_, returning their results in an ordered array of rejected and resolved results
77
+ * Handle keyed _Promises_, returning their results in a similarly keyed object
78
78
  *
79
- * @param items List of _Promises_
80
- * @param signal AbortSignal for aborting the operation _(when aborted, the _Promise_ will reject with the reason of the signal)_
81
- * @returns List of results
79
+ * @param items Keyed _Promises_
80
+ * @param signal _AbortSignal_ for aborting all _Promises_
81
+ * @returns Keyed object of results
82
82
  */
83
- declare function promises<Value>(items: Array<Promise<Value> | (() => Promise<Value>)>, signal?: AbortSignal): Promise<PromisesValue<Value>[]>;
83
+ declare function promises<Items extends PlainObject>(items: Items, signal?: AbortSignal): Promise<PromisesValues<PromisesItems<Items>>>;
84
84
  declare namespace promises {
85
85
  var result: typeof resultPromises;
86
86
  }
87
87
  /**
88
88
  * Handle a list of _Promises_, returning their results in an ordered array of results _({@link Result})_
89
89
  *
90
- * Depending on the strategy, the function will either reject on the first error encountered or return an array of rejected and resolved results
90
+ * _Depending on the strategy, the function will either reject on the first error encountered or return an array of rejected and resolved results_
91
91
  *
92
92
  * _Available as `resultPromises` and `promises.result`_
93
93
  *
94
94
  * @param items List of _Promises_
95
- * @param signal AbortSignal for aborting the operation _(when aborted, the _Promise_ will reject with the reason of the signal)_
95
+ * @param signal AbortSignal for aborting all _Promises_
96
96
  * @returns List of results
97
97
  */
98
98
  declare function resultPromises<Items extends unknown[]>(items: [...Items], signal?: AbortSignal): Promise<PromisesResult<PromisesItems<Items>>>;
99
99
  /**
100
- * Handle a list of _Promises_, returning their results in an ordered array of results _({@link Result})_
101
- *
102
- * Depending on the strategy, the function will either reject on the first error encountered or return an array of rejected and resolved results
100
+ * Handle keyed _Promises_, returning their results in a similarly keyed object of results _({@link Result})_
103
101
  *
104
102
  * _Available as `resultPromises` and `promises.result`_
105
103
  *
106
- * @param items List of _Promises_
107
- * @param signal AbortSignal for aborting the operation _(when aborted, the _Promise_ will reject with the reason of the signal)_
108
- * @returns List of results
104
+ * @param items Keyed _Promises_
105
+ * @param signal AbortSignal for aborting all _Promises_
106
+ * @returns Keyed object of results
109
107
  */
110
- declare function resultPromises<Value>(items: Promise<Value>[], signal?: AbortSignal): Promise<Result<Awaited<Value>>[]>;
108
+ declare function resultPromises<Items extends PlainObject>(items: Items, signal?: AbortSignal): Promise<PromisesResult<PromisesItems<Items>>>;
111
109
  //#endregion
112
110
  export { attemptPromise, promises, resultPromises };
@@ -1,5 +1,6 @@
1
+ import { isArrayOrPlainObject } from "../internal/is.mjs";
1
2
  import { createAborter } from "../internal/abort.mjs";
2
- import { PROMISE_MESSAGE_EXPECTATION_ATTEMPT, PROMISE_STRATEGY_DEFAULT, PROMISE_TYPE_FULFILLED, PROMISE_TYPE_REJECTED } from "./constants.mjs";
3
+ import { PROMISE_MESSAGE_EXPECTATION_ATTEMPT, PROMISE_MESSAGE_EXPECTATION_ITEMS_EMPTY, PROMISE_MESSAGE_EXPECTATION_ITEMS_TYPE, PROMISE_STRATEGY_DEFAULT, PROMISE_TYPE_FULFILLED, PROMISE_TYPE_REJECTED } from "./constants.mjs";
3
4
  import { createPromiseOptions, createPromisesOptions, getResultsFromPromises } from "./helpers.mjs";
4
5
  import { handleResult, settlePromise } from "./misc.mjs";
5
6
  import { getTimedPromise } from "./timed.mjs";
@@ -31,17 +32,18 @@ async function attemptPromise(value, options) {
31
32
  async function promises(items, options) {
32
33
  const { signal, strategy } = createPromisesOptions(options);
33
34
  if (signal?.aborted ?? false) return Promise.reject(signal?.reason);
34
- if (!Array.isArray(items)) return Promise.resolve([]);
35
- const actual = items.map((item) => typeof item === "function" ? item() : item).filter((item) => item instanceof Promise);
35
+ if (!isArrayOrPlainObject(items)) return Promise.reject(PROMISE_MESSAGE_EXPECTATION_ITEMS_TYPE);
36
+ const isArray = Array.isArray(items);
37
+ const actual = (isArray ? items.map((item, index) => [index, item]) : Object.entries(items)).map(([key, value]) => [key, typeof value === "function" ? value() : value]).filter(([, value]) => value instanceof Promise);
36
38
  const { length } = actual;
37
- if (length === 0) return Promise.resolve([]);
39
+ if (length === 0) return Promise.reject(PROMISE_MESSAGE_EXPECTATION_ITEMS_EMPTY);
38
40
  const complete = strategy === PROMISE_STRATEGY_DEFAULT;
39
41
  const aborter = createAborter(signal, () => {
40
42
  handlers.reject(signal?.reason);
41
43
  });
42
44
  const data = {
43
45
  last: length - 1,
44
- result: []
46
+ result: isArray ? [] : {}
45
47
  };
46
48
  let handlers;
47
49
  return new Promise((resolve, reject) => {
@@ -49,21 +51,24 @@ async function promises(items, options) {
49
51
  reject,
50
52
  resolve
51
53
  };
52
- for (let index = 0; index < length; index += 1) actual[index].then((value) => handleResult(PROMISE_TYPE_FULFILLED, {
53
- aborter,
54
- complete,
55
- data,
56
- handlers,
57
- index,
58
- value
59
- })).catch((reason) => handleResult(PROMISE_TYPE_REJECTED, {
60
- aborter,
61
- complete,
62
- data,
63
- handlers,
64
- index,
65
- value: reason
66
- }));
54
+ for (let index = 0; index < length; index += 1) {
55
+ const [key, promise] = actual[index];
56
+ const parameters = {
57
+ aborter,
58
+ complete,
59
+ data,
60
+ handlers,
61
+ index,
62
+ key
63
+ };
64
+ promise.then((value) => {
65
+ parameters.value = value;
66
+ handleResult(PROMISE_TYPE_FULFILLED, parameters);
67
+ }).catch((reason) => {
68
+ parameters.value = reason;
69
+ handleResult(PROMISE_TYPE_REJECTED, parameters);
70
+ });
71
+ }
67
72
  });
68
73
  }
69
74
  async function resultPromises(items, signal) {
@@ -14,13 +14,13 @@ function cancelable(executor) {
14
14
  return new CancelablePromise(executor);
15
15
  }
16
16
  function handleResult(status, parameters) {
17
- const { aborter, complete, data, handlers, index, value } = parameters;
17
+ const { aborter, complete, data, handlers, index, key, value } = parameters;
18
18
  if (aborter?.signal.aborted ?? false) return;
19
19
  if (!complete && status === "rejected") {
20
20
  settlePromise(handlers.reject, value, aborter);
21
21
  return;
22
22
  }
23
- data.result[index] = !complete ? value : status === "fulfilled" ? {
23
+ data.result[key] = !complete ? value : status === "fulfilled" ? {
24
24
  status,
25
25
  value
26
26
  } : {
@@ -1,4 +1,4 @@
1
- import { GenericCallback } from "../models.mjs";
1
+ import { ArrayOrPlainObject, GenericCallback, Key } from "../models.mjs";
2
2
  import { Result } from "../internal/result/models.mjs";
3
3
  import { Aborter } from "../internal/abort.mjs";
4
4
  import { PROMISE_TYPE_FULFILLED, PROMISE_TYPE_REJECTED } from "./constants.mjs";
@@ -31,7 +31,7 @@ type FulfilledPromise<Value> = {
31
31
  };
32
32
  type PromiseData = {
33
33
  last: number;
34
- result: unknown[];
34
+ result: ArrayOrPlainObject;
35
35
  };
36
36
  type PromiseHandlers = {
37
37
  resolve: (value: unknown[]) => void;
@@ -56,6 +56,7 @@ type PromiseParameters = {
56
56
  data: PromiseData;
57
57
  handlers: PromiseHandlers;
58
58
  index: number;
59
+ key: Key;
59
60
  value?: unknown;
60
61
  };
61
62
  /**
@@ -71,7 +72,7 @@ type PromiseStrategy = 'complete' | 'first';
71
72
  declare class PromiseTimeoutError extends Error {
72
73
  constructor();
73
74
  }
74
- type PromisesItems<Items extends unknown[]> = { [ItemsKey in keyof Items]: Items[ItemsKey] extends GenericCallback ? ReturnType<Items[ItemsKey]> extends Promise<infer Value> ? Promise<Value> : never : Items[ItemsKey] extends Promise<infer Value> ? Promise<Value> : Promise<Items[ItemsKey]>; };
75
+ type PromisesItems<Items extends ArrayOrPlainObject> = { [ItemsKey in keyof Items]: Items[ItemsKey] extends GenericCallback ? ReturnType<Items[ItemsKey]> extends Promise<infer Value> ? Promise<Value> : never : Items[ItemsKey] extends Promise<infer Value> ? Promise<Value> : Promise<Items[ItemsKey]>; };
75
76
  /**
76
77
  * Options for handling multiple _Promises_
77
78
  */
@@ -85,10 +86,10 @@ type PromisesOptions = {
85
86
  */
86
87
  strategy?: PromiseStrategy;
87
88
  };
88
- type PromisesResult<Items extends unknown[]> = { [ItemsKey in keyof Items]: Items[ItemsKey] extends Promise<infer Value> ? Result<Awaited<Value>> : never; };
89
- type PromisesUnwrapped<Items extends unknown[]> = { [ItemsKey in keyof Items]: Items[ItemsKey] extends GenericCallback ? ReturnType<Items[ItemsKey]> extends Promise<infer Value> ? Awaited<Value> : never : Items[ItemsKey] extends Promise<infer Value> ? Awaited<Value> : never; };
89
+ type PromisesResult<Items extends ArrayOrPlainObject> = { [ItemsKey in keyof Items]: Items[ItemsKey] extends Promise<infer Value> ? Result<Awaited<Value>> : never; };
90
+ type PromisesUnwrapped<Items extends ArrayOrPlainObject> = { [ItemsKey in keyof Items]: Items[ItemsKey] extends GenericCallback ? ReturnType<Items[ItemsKey]> extends Promise<infer Value> ? Awaited<Value> : never : Items[ItemsKey] extends Promise<infer Value> ? Awaited<Value> : never; };
90
91
  type PromisesValue<Value> = FulfilledPromise<Value> | RejectedPromise;
91
- type PromisesValues<Items extends unknown[]> = { [ItemsKey in keyof Items]: Items[ItemsKey] extends GenericCallback ? ReturnType<Items[ItemsKey]> extends Promise<infer Value> ? PromisesValue<Awaited<Value>> : never : Items[ItemsKey] extends Promise<infer Value> ? PromisesValue<Awaited<Value>> : never; };
92
+ type PromisesValues<Items extends ArrayOrPlainObject> = { [ItemsKey in keyof Items]: Items[ItemsKey] extends Promise<infer Value> ? PromisesValue<Awaited<Value>> : never; };
92
93
  /**
93
94
  * A _Promise_ that was rejected
94
95
  */