@naturalcycles/js-lib 15.107.0 → 15.109.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.
Files changed (59) hide show
  1. package/dist/abort.d.ts +6 -0
  2. package/dist/abort.js +18 -1
  3. package/dist/array/array.util.js +10 -4
  4. package/dist/array/sort.js +1 -1
  5. package/dist/browser/adminService.js +1 -1
  6. package/dist/datetime/localDate.js +4 -2
  7. package/dist/datetime/localTime.js +1 -1
  8. package/dist/decorators/asyncMemo.decorator.d.ts +1 -1
  9. package/dist/decorators/asyncMemo.decorator.js +88 -86
  10. package/dist/decorators/memo.decorator.d.ts +1 -1
  11. package/dist/decorators/memo.decorator.js +62 -60
  12. package/dist/decorators/memoSimple.decorator.d.ts +1 -1
  13. package/dist/decorators/memoSimple.decorator.js +39 -37
  14. package/dist/decorators/memoized.js +2 -2
  15. package/dist/decorators/memoizedAsync.js +2 -2
  16. package/dist/decorators/swarmSafe.decorator.d.ts +1 -1
  17. package/dist/decorators/swarmSafe.decorator.js +28 -26
  18. package/dist/define.js +2 -2
  19. package/dist/error/tryCatch.d.ts +1 -1
  20. package/dist/error/tryCatch.js +7 -5
  21. package/dist/http/fetch.js +2 -1
  22. package/dist/is.util.d.ts +6 -6
  23. package/dist/is.util.js +18 -6
  24. package/dist/log/commonLogger.js +6 -2
  25. package/dist/math/math.util.js +3 -3
  26. package/dist/object/keySortedMap.js +1 -0
  27. package/dist/object/lazyKeySortedMap.js +1 -0
  28. package/dist/promise/pMap.js +2 -2
  29. package/dist/qr/qr.js +3 -1
  30. package/dist/semver.js +4 -2
  31. package/dist/string/slugify.js +4 -6
  32. package/dist/types.d.ts +1 -1
  33. package/dist/types.js +3 -1
  34. package/package.json +2 -2
  35. package/src/abort.ts +20 -1
  36. package/src/array/array.util.ts +10 -4
  37. package/src/array/sort.ts +1 -1
  38. package/src/browser/adminService.ts +2 -1
  39. package/src/datetime/localDate.ts +6 -2
  40. package/src/datetime/localTime.ts +1 -1
  41. package/src/decorators/asyncMemo.decorator.ts +3 -3
  42. package/src/decorators/memo.decorator.ts +3 -3
  43. package/src/decorators/memoSimple.decorator.ts +14 -14
  44. package/src/decorators/memoized.ts +1 -1
  45. package/src/decorators/memoizedAsync.ts +1 -1
  46. package/src/decorators/swarmSafe.decorator.ts +29 -27
  47. package/src/define.ts +1 -1
  48. package/src/error/tryCatch.ts +3 -3
  49. package/src/http/fetch.ts +2 -1
  50. package/src/is.util.ts +22 -6
  51. package/src/log/commonLogger.ts +5 -2
  52. package/src/math/math.util.ts +3 -3
  53. package/src/object/keySortedMap.ts +1 -0
  54. package/src/object/lazyKeySortedMap.ts +1 -0
  55. package/src/promise/pMap.ts +1 -1
  56. package/src/qr/qr.ts +5 -1
  57. package/src/semver.ts +6 -2
  58. package/src/string/slugify.ts +7 -9
  59. package/src/types.ts +3 -1
@@ -7,31 +7,33 @@ import { _getTargetMethodSignature } from './decorator.util.js';
7
7
  * Does not support `cacheKey`.
8
8
  * So, the same Promise is returned, regardless of the arguments.
9
9
  */
10
- export const _SwarmSafe = () => (target, key, descriptor) => {
11
- if (typeof descriptor.value !== 'function') {
12
- throw new TypeError('@_SwarmSafe can be applied only to methods');
13
- }
14
- const originalFn = descriptor.value;
15
- const keyStr = String(key);
16
- const methodSignature = _getTargetMethodSignature(target, keyStr);
17
- const instanceCache = new Map();
18
- console.log('SwarmSafe constructor called', { key, methodSignature });
19
- // oxlint-disable-next-line @typescript-eslint/promise-function-async
20
- descriptor.value = function (...args) {
21
- console.log('SwarmSafe method called', { key, methodSignature, args });
22
- const ctx = this;
23
- let inFlightPromise = instanceCache.get(ctx);
24
- if (inFlightPromise) {
25
- console.log(`SwarmSafe: returning in-flight promise`);
26
- return inFlightPromise;
10
+ export function _SwarmSafe() {
11
+ return (target, key, descriptor) => {
12
+ if (typeof descriptor.value !== 'function') {
13
+ throw new TypeError('@_SwarmSafe can be applied only to methods');
27
14
  }
28
- console.log(`SwarmSafe: first-time call, creating in-flight promise`);
29
- inFlightPromise = originalFn.apply(ctx, args);
30
- instanceCache.set(ctx, inFlightPromise);
31
- void inFlightPromise.finally(() => {
32
- console.log(`SwarmSafe: in-flight promise resolved`);
33
- instanceCache.delete(ctx);
34
- });
35
- return inFlightPromise;
15
+ const originalFn = descriptor.value;
16
+ const keyStr = String(key);
17
+ const methodSignature = _getTargetMethodSignature(target, keyStr);
18
+ const instanceCache = new Map();
19
+ console.log('SwarmSafe constructor called', { key, methodSignature });
20
+ // oxlint-disable-next-line @typescript-eslint/promise-function-async
21
+ descriptor.value = function (...args) {
22
+ console.log('SwarmSafe method called', { key, methodSignature, args });
23
+ const ctx = this;
24
+ let inFlightPromise = instanceCache.get(ctx);
25
+ if (inFlightPromise) {
26
+ console.log(`SwarmSafe: returning in-flight promise`);
27
+ return inFlightPromise;
28
+ }
29
+ console.log(`SwarmSafe: first-time call, creating in-flight promise`);
30
+ inFlightPromise = originalFn.apply(ctx, args);
31
+ instanceCache.set(ctx, inFlightPromise);
32
+ void inFlightPromise.finally(() => {
33
+ console.log(`SwarmSafe: in-flight promise resolved`);
34
+ instanceCache.delete(ctx);
35
+ });
36
+ return inFlightPromise;
37
+ };
36
38
  };
37
- };
39
+ }
package/dist/define.js CHANGED
@@ -35,9 +35,9 @@ export function _lazyValue(fn) {
35
35
  * Based on: https://github.com/sindresorhus/define-lazy-prop
36
36
  */
37
37
  export function _defineLazyProperty(obj, propertyName, fn) {
38
- const define = (value) => {
38
+ function define(value) {
39
39
  Object.defineProperty(obj, propertyName, { value, enumerable: true, writable: true });
40
- };
40
+ }
41
41
  Object.defineProperty(obj, propertyName, {
42
42
  configurable: true,
43
43
  enumerable: true,
@@ -28,4 +28,4 @@ export interface TryCatchOptions {
28
28
  * @experimental
29
29
  */
30
30
  export declare function _tryCatch<T extends AnyFunction>(fn: T, opt?: TryCatchOptions): T;
31
- export declare const _TryCatch: (opt?: TryCatchOptions) => MethodDecorator;
31
+ export declare function _TryCatch(opt?: TryCatchOptions): MethodDecorator;
@@ -35,8 +35,10 @@ export function _tryCatch(fn, opt = {}) {
35
35
  }
36
36
  };
37
37
  }
38
- export const _TryCatch = (opt = {}) => (_target, _key, descriptor) => {
39
- const originalFn = descriptor.value;
40
- descriptor.value = _tryCatch(originalFn, opt);
41
- return descriptor;
42
- };
38
+ export function _TryCatch(opt = {}) {
39
+ return (_target, _key, descriptor) => {
40
+ const originalFn = descriptor.value;
41
+ descriptor.value = _tryCatch(originalFn, opt);
42
+ return descriptor;
43
+ };
44
+ }
@@ -1,4 +1,5 @@
1
1
  /// <reference lib="dom" preserve="true" />
2
+ import { abortSignalTimeoutOrUndefined } from '../abort.js';
2
3
  /**
3
4
  * Minimal wrapper around native `fetch`:
4
5
  *
@@ -24,7 +25,7 @@ export async function _fetch(url, opt = {}) {
24
25
  ...init,
25
26
  method,
26
27
  // A fresh signal per attempt, as a timed-out signal stays aborted
27
- signal: timeout ? AbortSignal.timeout(timeout) : undefined,
28
+ signal: abortSignalTimeoutOrUndefined(timeout),
28
29
  });
29
30
  if (res.ok) {
30
31
  const text = await res.text();
package/dist/is.util.d.ts CHANGED
@@ -2,10 +2,10 @@ import type { AnyObject, FalsyValue, NullishValue, PlainObject, Primitive } from
2
2
  type Nullish<T> = T extends NullishValue ? T : never;
3
3
  type Truthy<T> = T extends FalsyValue ? never : T;
4
4
  type Falsy<T> = T extends FalsyValue ? T : never;
5
- export declare const _isNull: <T>(v: T) => v is T extends null ? T : never;
6
- export declare const _isUndefined: <T>(v: T) => v is T extends undefined ? T : never;
7
- export declare const _isNullish: <T>(v: T) => v is Nullish<T>;
8
- export declare const _isNotNullish: <T>(v: T) => v is NonNullable<T>;
5
+ export declare function _isNull<T>(v: T): v is T extends null ? T : never;
6
+ export declare function _isUndefined<T>(v: T): v is T extends undefined ? T : never;
7
+ export declare function _isNullish<T>(v: T): v is Nullish<T>;
8
+ export declare function _isNotNullish<T>(v: T): v is NonNullable<T>;
9
9
  /**
10
10
  * Same as Boolean, but with correct type output.
11
11
  * Related:
@@ -17,8 +17,8 @@ export declare const _isNotNullish: <T>(v: T) => v is NonNullable<T>;
17
17
  * [1, 2, undefined].filter(_isTruthy)
18
18
  * // => [1, 2]
19
19
  */
20
- export declare const _isTruthy: <T>(v: T) => v is Truthy<T>;
21
- export declare const _isFalsy: <T>(v: T) => v is Falsy<T>;
20
+ export declare function _isTruthy<T>(v: T): v is Truthy<T>;
21
+ export declare function _isFalsy<T>(v: T): v is Falsy<T>;
22
22
  /**
23
23
  * Returns true if item is Object, not null and not Array.
24
24
  *
package/dist/is.util.js CHANGED
@@ -1,7 +1,15 @@
1
- export const _isNull = (v) => v === null;
2
- export const _isUndefined = (v) => v === undefined;
3
- export const _isNullish = (v) => v === undefined || v === null;
4
- export const _isNotNullish = (v) => v !== undefined && v !== null;
1
+ export function _isNull(v) {
2
+ return v === null;
3
+ }
4
+ export function _isUndefined(v) {
5
+ return v === undefined;
6
+ }
7
+ export function _isNullish(v) {
8
+ return v === undefined || v === null;
9
+ }
10
+ export function _isNotNullish(v) {
11
+ return v !== undefined && v !== null;
12
+ }
5
13
  /**
6
14
  * Same as Boolean, but with correct type output.
7
15
  * Related:
@@ -13,8 +21,12 @@ export const _isNotNullish = (v) => v !== undefined && v !== null;
13
21
  * [1, 2, undefined].filter(_isTruthy)
14
22
  * // => [1, 2]
15
23
  */
16
- export const _isTruthy = (v) => !!v;
17
- export const _isFalsy = (v) => !v;
24
+ export function _isTruthy(v) {
25
+ return !!v;
26
+ }
27
+ export function _isFalsy(v) {
28
+ return !v;
29
+ }
18
30
  /**
19
31
  * Returns true if item is Object, not null and not Array.
20
32
  *
@@ -1,5 +1,7 @@
1
1
  // copy-pasted to avoid weird circular dependency
2
- const _noop = (..._args) => undefined;
2
+ function _noop(..._args) {
3
+ return undefined;
4
+ }
3
5
  export const commonLogLevelNumber = {
4
6
  debug: 10,
5
7
  log: 20,
@@ -12,7 +14,9 @@ export const commonLogLevelNumber = {
12
14
  * after the logger is created (e.g a request context whose user is resolved later).
13
15
  */
14
16
  export function commonLoggerCreate(sink, context) {
15
- const emit = (level, [input, data]) => sink({ ...context?.(), ...toLogData(input, data), level });
17
+ function emit(level, [input, data]) {
18
+ sink({ ...context?.(), ...toLogData(input, data), level });
19
+ }
16
20
  return {
17
21
  debug: (...args) => emit('debug', args),
18
22
  log: (...args) => emit('log', args),
@@ -70,7 +70,7 @@ export function _averageWeighted(values, weights) {
70
70
  * // 3
71
71
  */
72
72
  export function _percentile(values, pc) {
73
- const sorted = values.toSorted(comparators.numericAsc);
73
+ const sorted = values.slice().sort(comparators.numericAsc);
74
74
  // Floating pos in the range of [0; length - 1]
75
75
  const pos = ((values.length - 1) * pc) / 100;
76
76
  const dec = pos % 1;
@@ -83,7 +83,7 @@ export function _percentile(values, pc) {
83
83
  */
84
84
  export function _percentiles(values, pcs) {
85
85
  const r = {};
86
- const sorted = values.toSorted(comparators.numericAsc);
86
+ const sorted = values.slice().sort(comparators.numericAsc);
87
87
  for (const pc of pcs) {
88
88
  // Floating pos in the range of [0; length - 1]
89
89
  const pos = ((values.length - 1) * pc) / 100;
@@ -104,7 +104,7 @@ export function _percentiles(values, pcs) {
104
104
  * // 2.5
105
105
  */
106
106
  export function _median(values) {
107
- const sorted = values.toSorted(comparators.numericAsc);
107
+ const sorted = values.slice().sort(comparators.numericAsc);
108
108
  const len = sorted.length;
109
109
  const mid = Math.floor(len / 2);
110
110
  return len % 2 ? sorted[mid] : (sorted[mid - 1] + sorted[mid]) / 2;
@@ -1,4 +1,5 @@
1
1
  import { _assert } from '../error/assert.js';
2
+ // oxlint-disable-next-line no-unsafe-declaration-merging -- see the interface above
2
3
  export class KeySortedMap {
3
4
  map;
4
5
  #sortedKeys;
@@ -1,4 +1,5 @@
1
1
  import { _assert } from '../error/assert.js';
2
+ // oxlint-disable-next-line no-unsafe-declaration-merging -- see the interface above
2
3
  export class LazyKeySortedMap {
3
4
  map;
4
5
  maybeSortedKeys;
@@ -57,7 +57,7 @@ export async function pMap(iterable, mapper, opt = {}) {
57
57
  let resolvingCount = 0;
58
58
  let currentIndex = 0;
59
59
  return await new Promise((resolve, reject) => {
60
- const next = () => {
60
+ function next() {
61
61
  if (isSettled) {
62
62
  return;
63
63
  }
@@ -104,7 +104,7 @@ export async function pMap(iterable, mapper, opt = {}) {
104
104
  next(); // oxlint-disable-line no-callback-in-promise
105
105
  }
106
106
  });
107
- };
107
+ }
108
108
  for (let i = 0; i < concurrency; i++) {
109
109
  next();
110
110
  if (isSettled) {
package/dist/qr/qr.js CHANGED
@@ -426,7 +426,9 @@ function lostPointBlocks(modules) {
426
426
  function lostPointFinderLike(modules) {
427
427
  const size = modules.length;
428
428
  let lostPoint = 0;
429
- const isDark = (r, c) => modules[r][c] === true;
429
+ function isDark(r, c) {
430
+ return modules[r][c] === true;
431
+ }
430
432
  for (let row = 0; row < size; row++) {
431
433
  for (let col = 0; col < size - 6; col++) {
432
434
  if (isDark(row, col) &&
package/dist/semver.js CHANGED
@@ -122,8 +122,10 @@ class SemverFactory {
122
122
  */
123
123
  sort(items, opt = {}) {
124
124
  const mod = opt.dir === 'desc' ? -1 : 1;
125
- const cmp = (a, b) => a.compare(b) * mod;
126
- return opt.mutate ? items.sort(cmp) : items.toSorted(cmp);
125
+ function cmp(a, b) {
126
+ return a.compare(b) * mod;
127
+ }
128
+ return opt.mutate ? items.sort(cmp) : items.slice().sort(cmp);
127
129
  }
128
130
  }
129
131
  // Built inside a function, so the whole construct can be marked pure and tree-shaken (see treeshake.test.ts)
@@ -31,13 +31,11 @@ export function _slugify(s, opt = {}) {
31
31
  function buildPatternSlug(options) {
32
32
  let negationSetPattern = String.raw `a-z\d`;
33
33
  negationSetPattern += options.lowercase ? '' : 'A-Z';
34
- if (options.preserveCharacters.length > 0) {
35
- for (const character of options.preserveCharacters) {
36
- if (character === options.separator) {
37
- throw new Error(`The separator character \`${options.separator}\` cannot be included in preserved characters: ${options.preserveCharacters}`);
38
- }
39
- negationSetPattern += escapeStringRegexp(character);
34
+ for (const character of options.preserveCharacters) {
35
+ if (character === options.separator) {
36
+ throw new Error(`The separator character \`${options.separator}\` cannot be included in preserved characters: ${options.preserveCharacters}`);
40
37
  }
38
+ negationSetPattern += escapeStringRegexp(character);
41
39
  }
42
40
  return new RegExp(`[^${negationSetPattern}]+`, 'g');
43
41
  }
package/dist/types.d.ts CHANGED
@@ -151,7 +151,7 @@ export declare const _passUndefinedMapper: IndexedMapper<any, void>;
151
151
  /**
152
152
  * Function that does nothings and returns `undefined`.
153
153
  */
154
- export declare const _noop: (..._args: any[]) => undefined;
154
+ export declare function _noop(..._args: any[]): undefined;
155
155
  export type Predicate<T> = (item: T, index: number) => boolean;
156
156
  export type AsyncPredicate<T> = (item: T, index: number) => PromiseLike<boolean>;
157
157
  export type AbortablePredicate<T> = (item: T, i: number) => boolean | typeof END;
package/dist/types.js CHANGED
@@ -16,7 +16,9 @@ export const _passUndefinedMapper = () => undefined;
16
16
  /**
17
17
  * Function that does nothings and returns `undefined`.
18
18
  */
19
- export const _noop = (..._args) => undefined;
19
+ export function _noop(..._args) {
20
+ return undefined;
21
+ }
20
22
  export const _passthroughPredicate = () => true;
21
23
  export const _passNothingPredicate = () => false;
22
24
  export const JWT_REGEX = /^[\w-]+\.[\w-]+\.[\w-]+$/;
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@naturalcycles/js-lib",
3
3
  "type": "module",
4
- "version": "15.107.0",
4
+ "version": "15.109.0",
5
5
  "dependencies": {
6
6
  "tslib": "^2"
7
7
  },
@@ -14,7 +14,7 @@
14
14
  }
15
15
  },
16
16
  "devDependencies": {
17
- "@naturalcycles/dev-lib": "20.79.0",
17
+ "@naturalcycles/dev-lib": "20.81.0",
18
18
  "@types/node": "^26",
19
19
  "@types/semver": "^7",
20
20
  "rolldown": "^1",
package/src/abort.ts CHANGED
@@ -39,7 +39,26 @@ export function createAbortableSignal(): AbortableSignal {
39
39
  export function abortSignalTimeoutOrUndefined(
40
40
  ms: NumberOfMilliseconds | undefined,
41
41
  ): AbortSignal | undefined {
42
- return ms ? AbortSignal.timeout(ms) : undefined
42
+ return ms ? abortSignalTimeout(ms) : undefined
43
+ }
44
+
45
+ /**
46
+ * Returns an AbortSignal that aborts after `ms` with a "TimeoutError" DOMException.
47
+ * Uses native `AbortSignal.timeout()` when available, falls back to a polyfill.
48
+ */
49
+ export function abortSignalTimeout(ms: NumberOfMilliseconds): AbortSignal {
50
+ // AbortSignal.timeout needs Chrome 103+ / Safari 16+, below our browser floor (Chrome 110, iOS 16.7),
51
+ // but Fetcher calls it on every request and browsers like iOS 15 still visit our sites
52
+ return typeof AbortSignal.timeout === 'function'
53
+ ? AbortSignal.timeout(ms)
54
+ : polyfilledAbortSignalTimeout(ms)
55
+ }
56
+
57
+ export function polyfilledAbortSignalTimeout(ms: NumberOfMilliseconds): AbortSignal {
58
+ const ac = new AbortController()
59
+ // Same reason as the native one, Fetcher tells a timeout from an abort by its name
60
+ setTimeout(() => ac.abort(new DOMException('signal timed out', 'TimeoutError')), ms)
61
+ return ac.signal
43
62
  }
44
63
 
45
64
  /**
@@ -198,7 +198,7 @@ export function _find<T>(items: readonly T[], predicate: AbortablePredicate<T>):
198
198
  * Use `Array.findLast` if you don't need to stop the iteration early.
199
199
  */
200
200
  export function _findLast<T>(items: readonly T[], predicate: AbortablePredicate<T>): T | undefined {
201
- return _find(items.toReversed(), predicate)
201
+ return _find(items.slice().reverse(), predicate)
202
202
  }
203
203
 
204
204
  export function _takeWhile<T>(items: readonly T[], predicate: Predicate<T>): T[] {
@@ -208,7 +208,10 @@ export function _takeWhile<T>(items: readonly T[], predicate: Predicate<T>): T[]
208
208
 
209
209
  export function _takeRightWhile<T>(items: readonly T[], predicate: Predicate<T>): T[] {
210
210
  let proceed = true
211
- return items.toReversed().filter((v, index) => (proceed &&= predicate(v, index)))
211
+ return items
212
+ .slice()
213
+ .reverse()
214
+ .filter((v, index) => (proceed &&= predicate(v, index)))
212
215
  }
213
216
 
214
217
  export function _dropWhile<T>(items: readonly T[], predicate: Predicate<T>): T[] {
@@ -219,7 +222,8 @@ export function _dropWhile<T>(items: readonly T[], predicate: Predicate<T>): T[]
219
222
  export function _dropRightWhile<T>(items: readonly T[], predicate: Predicate<T>): T[] {
220
223
  let proceed = false
221
224
  return items
222
- .toReversed()
225
+ .slice()
226
+ .reverse()
223
227
  .filter((v, index) => (proceed ||= !predicate(v, index)))
224
228
  .reverse()
225
229
  }
@@ -426,7 +430,9 @@ export function _shuffle<T>(array: T[], opt: MutateOptions = {}): T[] {
426
430
 
427
431
  for (let i = a.length - 1; i > 0; i--) {
428
432
  const j = Math.floor(Math.random() * (i + 1))
429
- ;[a[i], a[j]] = [a[j]!, a[i]!]
433
+ const tmp = a[i]!
434
+ a[i] = a[j]!
435
+ a[j] = tmp
430
436
  }
431
437
 
432
438
  return a
package/src/array/sort.ts CHANGED
@@ -77,7 +77,7 @@ export function _sortBy<T, COMPARE_TYPE extends string | number>(
77
77
  opt: SortOptions = {},
78
78
  ): T[] {
79
79
  const cmp = comparators.by(mapper, opt)
80
- return opt.mutate ? items.sort(cmp) : items.toSorted(cmp)
80
+ return opt.mutate ? items.sort(cmp) : items.slice().sort(cmp)
81
81
  }
82
82
 
83
83
  /**
@@ -56,7 +56,8 @@ export interface AdminModeCfg {
56
56
  }
57
57
 
58
58
  const RED_DOT_ID = '__red-dot__'
59
- const NOOP = (): void => {}
59
+
60
+ function NOOP(): void {}
60
61
 
61
62
  /**
62
63
  * @experimental
@@ -725,8 +725,12 @@ class LocalDateFactory {
725
725
  */
726
726
  sort(items: LocalDate[], opt: SortOptions = {}): LocalDate[] {
727
727
  const mod = opt.dir === 'desc' ? -1 : 1
728
- const cmp = (a: LocalDate, b: LocalDate): number => a.compare(b) * mod
729
- return opt.mutate ? items.sort(cmp) : items.toSorted(cmp)
728
+
729
+ function cmp(a: LocalDate, b: LocalDate): number {
730
+ return a.compare(b) * mod
731
+ }
732
+
733
+ return opt.mutate ? items.sort(cmp) : items.slice().sort(cmp)
730
734
  }
731
735
 
732
736
  /**
@@ -1027,7 +1027,7 @@ class LocalTimeFactory {
1027
1027
 
1028
1028
  sort(items: LocalTime[], dir: SortDirection = 'asc', opt: MutateOptions = {}): LocalTime[] {
1029
1029
  const cmp = comparators.by((lt: LocalTime) => lt.$date.valueOf(), { dir })
1030
- return opt.mutate ? items.sort(cmp) : items.toSorted(cmp)
1030
+ return opt.mutate ? items.sort(cmp) : items.slice().sort(cmp)
1031
1031
  }
1032
1032
 
1033
1033
  minOrUndefined(items: readonly LocalTimeInputNullable[]): LocalTime | undefined {
@@ -53,9 +53,8 @@ export interface AsyncMemoInstance {
53
53
  * Implementation is more complex than `@_Memo`, because it needs to handle "in-flight" Promises
54
54
  * while waiting for cache to resolve, to prevent "async swarm" issue.
55
55
  */
56
- export const _AsyncMemo =
57
- <FN>(opt: AsyncMemoOptions<FN> = {}): MethodDecorator<FN> =>
58
- (target, key, descriptor) => {
56
+ export function _AsyncMemo<FN>(opt: AsyncMemoOptions<FN> = {}): MethodDecorator<FN> {
57
+ return (target, key, descriptor) => {
59
58
  _assertTypeOf<AnyFunction>(
60
59
  descriptor.value,
61
60
  'function',
@@ -171,6 +170,7 @@ export const _AsyncMemo =
171
170
 
172
171
  return descriptor
173
172
  }
173
+ }
174
174
 
175
175
  /**
176
176
  Call it on a method that is decorated with `@_AsyncMemo` to get access to additional functions,
@@ -63,9 +63,8 @@ export interface MemoInstance {
63
63
  * http://inlehmansterms.net/2015/03/01/javascript-memoization/
64
64
  * https://community.risingstack.com/the-worlds-fastest-javascript-memoization-library/
65
65
  */
66
- export const _Memo =
67
- <FN>(opt: MemoOptions<FN> = {}): MethodDecorator<FN> =>
68
- (target, key, descriptor) => {
66
+ export function _Memo<FN>(opt: MemoOptions<FN> = {}): MethodDecorator<FN> {
67
+ return (target, key, descriptor) => {
69
68
  _assertTypeOf<AnyFunction>(
70
69
  descriptor.value,
71
70
  'function',
@@ -144,6 +143,7 @@ export const _Memo =
144
143
 
145
144
  return descriptor
146
145
  }
146
+ }
147
147
 
148
148
  /**
149
149
  Call it on a method that is decorated with `@_Memo` to get access to additional functions,
@@ -31,9 +31,8 @@ export interface MemoOpts {
31
31
  *
32
32
  * Supports dropping it's cache by calling .dropCache() method of decorated function (useful in unit testing).
33
33
  */
34
- export const memoSimple =
35
- (opt: MemoOpts = {}): MethodDecorator =>
36
- (target, key, descriptor) => {
34
+ export function memoSimple(opt: MemoOpts = {}): MethodDecorator {
35
+ return (target, key, descriptor) => {
37
36
  if (typeof descriptor.value !== 'function') {
38
37
  throw new TypeError('Memoization can be applied only to methods')
39
38
  }
@@ -43,17 +42,17 @@ export const memoSimple =
43
42
 
44
43
  // todo: optimization disabled until "default arg value" use case is solved (see memo.decorator.test.ts)
45
44
  /*
46
- let cache: MemoCache
47
-
48
- // Function with 0 arguments
49
- if (!originalFn.length) {
50
- cache = new SingleValueMemoCache()
51
- } else {
52
- // Function with > 0 arguments
53
- cache = new MapMemoCache()
54
- // cache = new ObjectMemoCache()
55
- }
56
- */
45
+ let cache: MemoCache
46
+
47
+ // Function with 0 arguments
48
+ if (!originalFn.length) {
49
+ cache = new SingleValueMemoCache()
50
+ } else {
51
+ // Function with > 0 arguments
52
+ cache = new MapMemoCache()
53
+ // cache = new ObjectMemoCache()
54
+ }
55
+ */
57
56
  const cache: MemoCache = new MapMemoCache()
58
57
 
59
58
  const { logger = consoleLogger } = opt
@@ -79,3 +78,4 @@ export const memoSimple =
79
78
 
80
79
  return descriptor
81
80
  }
81
+ }
@@ -25,7 +25,7 @@ export function _memoized<FN extends AnyFunction>(
25
25
 
26
26
  const cache = cacheFactory()
27
27
 
28
- const memoizedFn = function (this: any, ...args: MaybeParameters<FN>): FN {
28
+ function memoizedFn(this: any, ...args: MaybeParameters<FN>): FN {
29
29
  const ctx = this
30
30
  const cacheKey = cacheKeyFn(args)
31
31
 
@@ -27,7 +27,7 @@ export function _memoizedAsync<FN extends AnyAsyncFunction>(
27
27
 
28
28
  const cache = cacheFactory()
29
29
 
30
- const memoizedFn = async function (this: any, ...args: MaybeParameters<FN>): Promise<any> {
30
+ async function memoizedFn(this: any, ...args: MaybeParameters<FN>): Promise<any> {
31
31
  const ctx = this
32
32
  const cacheKey = cacheKeyFn(args)
33
33
  // MISS, so that a failed cache `get` is a miss too (and not a cached `undefined`)
@@ -9,38 +9,40 @@ import { _getTargetMethodSignature } from './decorator.util.js'
9
9
  * Does not support `cacheKey`.
10
10
  * So, the same Promise is returned, regardless of the arguments.
11
11
  */
12
- export const _SwarmSafe = (): MethodDecorator => (target, key, descriptor) => {
13
- if (typeof descriptor.value !== 'function') {
14
- throw new TypeError('@_SwarmSafe can be applied only to methods')
15
- }
12
+ export function _SwarmSafe(): MethodDecorator {
13
+ return (target, key, descriptor) => {
14
+ if (typeof descriptor.value !== 'function') {
15
+ throw new TypeError('@_SwarmSafe can be applied only to methods')
16
+ }
16
17
 
17
- const originalFn = descriptor.value
18
- const keyStr = String(key)
19
- const methodSignature = _getTargetMethodSignature(target, keyStr)
20
- const instanceCache = new Map<AnyObject, Promise<any>>()
18
+ const originalFn = descriptor.value
19
+ const keyStr = String(key)
20
+ const methodSignature = _getTargetMethodSignature(target, keyStr)
21
+ const instanceCache = new Map<AnyObject, Promise<any>>()
21
22
 
22
- console.log('SwarmSafe constructor called', { key, methodSignature })
23
+ console.log('SwarmSafe constructor called', { key, methodSignature })
23
24
 
24
- // oxlint-disable-next-line @typescript-eslint/promise-function-async
25
- descriptor.value = function (this: typeof target, ...args: any[]): Promise<any> {
26
- console.log('SwarmSafe method called', { key, methodSignature, args })
27
- const ctx = this
25
+ // oxlint-disable-next-line @typescript-eslint/promise-function-async
26
+ descriptor.value = function (this: typeof target, ...args: any[]): Promise<any> {
27
+ console.log('SwarmSafe method called', { key, methodSignature, args })
28
+ const ctx = this
28
29
 
29
- let inFlightPromise = instanceCache.get(ctx)
30
- if (inFlightPromise) {
31
- console.log(`SwarmSafe: returning in-flight promise`)
32
- return inFlightPromise
33
- }
30
+ let inFlightPromise = instanceCache.get(ctx)
31
+ if (inFlightPromise) {
32
+ console.log(`SwarmSafe: returning in-flight promise`)
33
+ return inFlightPromise
34
+ }
34
35
 
35
- console.log(`SwarmSafe: first-time call, creating in-flight promise`)
36
+ console.log(`SwarmSafe: first-time call, creating in-flight promise`)
36
37
 
37
- inFlightPromise = originalFn.apply(ctx, args) as Promise<any>
38
- instanceCache.set(ctx, inFlightPromise)
39
- void inFlightPromise.finally(() => {
40
- console.log(`SwarmSafe: in-flight promise resolved`)
41
- instanceCache.delete(ctx)
42
- })
38
+ inFlightPromise = originalFn.apply(ctx, args) as Promise<any>
39
+ instanceCache.set(ctx, inFlightPromise)
40
+ void inFlightPromise.finally(() => {
41
+ console.log(`SwarmSafe: in-flight promise resolved`)
42
+ instanceCache.delete(ctx)
43
+ })
43
44
 
44
- return inFlightPromise
45
- } as any
45
+ return inFlightPromise
46
+ } as any
47
+ }
46
48
  }