@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
package/dist/abort.d.ts CHANGED
@@ -28,6 +28,12 @@ export declare function createAbortableSignal(): AbortableSignal;
28
28
  * Otherwise returns undefined.
29
29
  */
30
30
  export declare function abortSignalTimeoutOrUndefined(ms: NumberOfMilliseconds | undefined): AbortSignal | undefined;
31
+ /**
32
+ * Returns an AbortSignal that aborts after `ms` with a "TimeoutError" DOMException.
33
+ * Uses native `AbortSignal.timeout()` when available, falls back to a polyfill.
34
+ */
35
+ export declare function abortSignalTimeout(ms: NumberOfMilliseconds): AbortSignal;
36
+ export declare function polyfilledAbortSignalTimeout(ms: NumberOfMilliseconds): AbortSignal;
31
37
  /**
32
38
  * Returns AbortSignal.any(signals) is the array (after filtering undefined inputs) is not empty,
33
39
  * otherwise undefined.
package/dist/abort.js CHANGED
@@ -16,7 +16,24 @@ export function createAbortableSignal() {
16
16
  * Otherwise returns undefined.
17
17
  */
18
18
  export function abortSignalTimeoutOrUndefined(ms) {
19
- return ms ? AbortSignal.timeout(ms) : undefined;
19
+ return ms ? abortSignalTimeout(ms) : undefined;
20
+ }
21
+ /**
22
+ * Returns an AbortSignal that aborts after `ms` with a "TimeoutError" DOMException.
23
+ * Uses native `AbortSignal.timeout()` when available, falls back to a polyfill.
24
+ */
25
+ export function abortSignalTimeout(ms) {
26
+ // AbortSignal.timeout needs Chrome 103+ / Safari 16+, below our browser floor (Chrome 110, iOS 16.7),
27
+ // but Fetcher calls it on every request and browsers like iOS 15 still visit our sites
28
+ return typeof AbortSignal.timeout === 'function'
29
+ ? AbortSignal.timeout(ms)
30
+ : polyfilledAbortSignalTimeout(ms);
31
+ }
32
+ export function polyfilledAbortSignalTimeout(ms) {
33
+ const ac = new AbortController();
34
+ // Same reason as the native one, Fetcher tells a timeout from an abort by its name
35
+ setTimeout(() => ac.abort(new DOMException('signal timed out', 'TimeoutError')), ms);
36
+ return ac.signal;
20
37
  }
21
38
  /**
22
39
  * Returns AbortSignal.any(signals) is the array (after filtering undefined inputs) is not empty,
@@ -177,7 +177,7 @@ export function _find(items, predicate) {
177
177
  * Use `Array.findLast` if you don't need to stop the iteration early.
178
178
  */
179
179
  export function _findLast(items, predicate) {
180
- return _find(items.toReversed(), predicate);
180
+ return _find(items.slice().reverse(), predicate);
181
181
  }
182
182
  export function _takeWhile(items, predicate) {
183
183
  let proceed = true;
@@ -185,7 +185,10 @@ export function _takeWhile(items, predicate) {
185
185
  }
186
186
  export function _takeRightWhile(items, predicate) {
187
187
  let proceed = true;
188
- return items.toReversed().filter((v, index) => (proceed &&= predicate(v, index)));
188
+ return items
189
+ .slice()
190
+ .reverse()
191
+ .filter((v, index) => (proceed &&= predicate(v, index)));
189
192
  }
190
193
  export function _dropWhile(items, predicate) {
191
194
  let proceed = false;
@@ -194,7 +197,8 @@ export function _dropWhile(items, predicate) {
194
197
  export function _dropRightWhile(items, predicate) {
195
198
  let proceed = false;
196
199
  return items
197
- .toReversed()
200
+ .slice()
201
+ .reverse()
198
202
  .filter((v, index) => (proceed ||= !predicate(v, index)))
199
203
  .reverse();
200
204
  }
@@ -362,7 +366,9 @@ export function _shuffle(array, opt = {}) {
362
366
  const a = opt.mutate ? array : array.slice();
363
367
  for (let i = a.length - 1; i > 0; i--) {
364
368
  const j = Math.floor(Math.random() * (i + 1));
365
- [a[i], a[j]] = [a[j], a[i]];
369
+ const tmp = a[i];
370
+ a[i] = a[j];
371
+ a[j] = tmp;
366
372
  }
367
373
  return a;
368
374
  }
@@ -52,7 +52,7 @@ export const comparators = /* @__PURE__ */ new Comparators();
52
52
  */
53
53
  export function _sortBy(items, mapper, opt = {}) {
54
54
  const cmp = comparators.by(mapper, opt);
55
- return opt.mutate ? items.sort(cmp) : items.toSorted(cmp);
55
+ return opt.mutate ? items.sort(cmp) : items.slice().sort(cmp);
56
56
  }
57
57
  /**
58
58
  * Like _stringMapValues, but values are sorted.
@@ -3,7 +3,7 @@ import { _Memo } from '../decorators/memo.decorator.js';
3
3
  import { isServerSide } from '../env.js';
4
4
  import { _stringify } from '../string/stringify.js';
5
5
  const RED_DOT_ID = '__red-dot__';
6
- const NOOP = () => { };
6
+ function NOOP() { }
7
7
  /**
8
8
  * @experimental
9
9
  *
@@ -619,8 +619,10 @@ class LocalDateFactory {
619
619
  */
620
620
  sort(items, opt = {}) {
621
621
  const mod = opt.dir === 'desc' ? -1 : 1;
622
- const cmp = (a, b) => a.compare(b) * mod;
623
- return opt.mutate ? items.sort(cmp) : items.toSorted(cmp);
622
+ function cmp(a, b) {
623
+ return a.compare(b) * mod;
624
+ }
625
+ return opt.mutate ? items.sort(cmp) : items.slice().sort(cmp);
624
626
  }
625
627
  /**
626
628
  * Returns the earliest (min) LocalDate from the array, or undefined if the array is empty.
@@ -876,7 +876,7 @@ class LocalTimeFactory {
876
876
  }
877
877
  sort(items, dir = 'asc', opt = {}) {
878
878
  const cmp = comparators.by((lt) => lt.$date.valueOf(), { dir });
879
- return opt.mutate ? items.sort(cmp) : items.toSorted(cmp);
879
+ return opt.mutate ? items.sort(cmp) : items.slice().sort(cmp);
880
880
  }
881
881
  minOrUndefined(items) {
882
882
  let min;
@@ -41,7 +41,7 @@ export interface AsyncMemoInstance {
41
41
  * Implementation is more complex than `@_Memo`, because it needs to handle "in-flight" Promises
42
42
  * while waiting for cache to resolve, to prevent "async swarm" issue.
43
43
  */
44
- export declare const _AsyncMemo: <FN>(opt?: AsyncMemoOptions<FN>) => MethodDecorator<FN>;
44
+ export declare function _AsyncMemo<FN>(opt?: AsyncMemoOptions<FN>): MethodDecorator<FN>;
45
45
  /**
46
46
  Call it on a method that is decorated with `@_AsyncMemo` to get access to additional functions,
47
47
  e.g `clear` to clear the cache, or get its underlying data.
@@ -16,96 +16,98 @@ import { jsonMemoSerializer, MapAsyncMemoCache } from './memo.util.js';
16
16
  * Implementation is more complex than `@_Memo`, because it needs to handle "in-flight" Promises
17
17
  * while waiting for cache to resolve, to prevent "async swarm" issue.
18
18
  */
19
- export const _AsyncMemo = (opt = {}) => (target, key, descriptor) => {
20
- _assertTypeOf(descriptor.value, 'function', 'Memoization can be applied only to methods');
21
- const originalFn = descriptor.value;
22
- // Map from "instance" of the Class where @_AsyncMemo is applied to AsyncMemoCache instance.
23
- const instanceCache = new Map();
24
- // Cache from Instance to Map<key, Promise>
25
- // This cache is temporary, with only one purpose - to prevent "async swarm"
26
- // It only holds values that are "in-flight", until Promise is resolved
27
- // After it's resolved - it's evicted from the cache and moved to the "proper" `instanceCache`
28
- const instancePromiseCache = new Map();
29
- const { logger = consoleLogger, cacheFactory = () => new MapAsyncMemoCache(), cacheKeyFn = jsonMemoSerializer, } = opt;
30
- const keyStr = String(key);
31
- const methodSignature = _getTargetMethodSignature(target, keyStr);
32
- // oxlint-disable-next-line @typescript-eslint/promise-function-async
33
- descriptor.value = function (...args) {
34
- const ctx = this;
35
- const cacheKey = cacheKeyFn(args);
36
- let cache = instanceCache.get(ctx);
37
- let promiseCache = instancePromiseCache.get(ctx);
38
- if (!cache) {
39
- cache = cacheFactory();
40
- instanceCache.set(ctx, cache);
41
- // here, no need to check the cache. It's definitely a miss, because the cacheLayers is just created
42
- // UPD: no! AsyncMemo supports "persistent caches" (e.g Database-backed cache)
43
- }
44
- if (!promiseCache) {
45
- promiseCache = new Map();
46
- instancePromiseCache.set(ctx, promiseCache);
47
- }
48
- let promise = promiseCache.get(cacheKey);
49
- // If there's already "in-flight" cache request - return that, to avoid "async swarm"
50
- if (promise) {
51
- // console.log('return promise', promiseCache.size)
52
- return promise;
53
- }
54
- promise = cache.get(cacheKey).then(async (value) => {
55
- if (value !== MISS) {
56
- // console.log('hit', promiseCache.size)
57
- promiseCache.delete(cacheKey);
58
- return value;
19
+ export function _AsyncMemo(opt = {}) {
20
+ return (target, key, descriptor) => {
21
+ _assertTypeOf(descriptor.value, 'function', 'Memoization can be applied only to methods');
22
+ const originalFn = descriptor.value;
23
+ // Map from "instance" of the Class where @_AsyncMemo is applied to AsyncMemoCache instance.
24
+ const instanceCache = new Map();
25
+ // Cache from Instance to Map<key, Promise>
26
+ // This cache is temporary, with only one purpose - to prevent "async swarm"
27
+ // It only holds values that are "in-flight", until Promise is resolved
28
+ // After it's resolved - it's evicted from the cache and moved to the "proper" `instanceCache`
29
+ const instancePromiseCache = new Map();
30
+ const { logger = consoleLogger, cacheFactory = () => new MapAsyncMemoCache(), cacheKeyFn = jsonMemoSerializer, } = opt;
31
+ const keyStr = String(key);
32
+ const methodSignature = _getTargetMethodSignature(target, keyStr);
33
+ // oxlint-disable-next-line @typescript-eslint/promise-function-async
34
+ descriptor.value = function (...args) {
35
+ const ctx = this;
36
+ const cacheKey = cacheKeyFn(args);
37
+ let cache = instanceCache.get(ctx);
38
+ let promiseCache = instancePromiseCache.get(ctx);
39
+ if (!cache) {
40
+ cache = cacheFactory();
41
+ instanceCache.set(ctx, cache);
42
+ // here, no need to check the cache. It's definitely a miss, because the cacheLayers is just created
43
+ // UPD: no! AsyncMemo supports "persistent caches" (e.g Database-backed cache)
59
44
  }
60
- // Miss
61
- // console.log('miss', promiseCache.size)
62
- return await onMiss();
63
- }, async (err) => {
64
- // Log the cache error and proceed "as cache Miss"
65
- logger.error({ err });
66
- return await onMiss();
67
- });
68
- promiseCache.set(cacheKey, promise);
69
- return promise;
70
- //
71
- async function onMiss() {
72
- try {
73
- const value = await originalFn.apply(ctx, args);
74
- // Save the value in the Cache, in parallel,
75
- // not to slow down the main function execution
76
- // and not to fail on possible cache issues
77
- void (async () => {
78
- try {
79
- await cache.set(cacheKey, value);
80
- }
81
- catch (err) {
82
- logger.error({ err }); // log and ignore the error
83
- }
84
- finally {
85
- // Clear the "in-flight" promise cache entry, as we now have a "permanent" cache entry
86
- promiseCache.delete(cacheKey);
87
- // console.log('cache set and cleared', promiseCache!.size)
88
- }
89
- })();
90
- return value;
45
+ if (!promiseCache) {
46
+ promiseCache = new Map();
47
+ instancePromiseCache.set(ctx, promiseCache);
48
+ }
49
+ let promise = promiseCache.get(cacheKey);
50
+ // If there's already "in-flight" cache request - return that, to avoid "async swarm"
51
+ if (promise) {
52
+ // console.log('return promise', promiseCache.size)
53
+ return promise;
91
54
  }
92
- catch (err) {
93
- promiseCache.delete(cacheKey);
94
- throw err;
55
+ promise = cache.get(cacheKey).then(async (value) => {
56
+ if (value !== MISS) {
57
+ // console.log('hit', promiseCache.size)
58
+ promiseCache.delete(cacheKey);
59
+ return value;
60
+ }
61
+ // Miss
62
+ // console.log('miss', promiseCache.size)
63
+ return await onMiss();
64
+ }, async (err) => {
65
+ // Log the cache error and proceed "as cache Miss"
66
+ logger.error({ err });
67
+ return await onMiss();
68
+ });
69
+ promiseCache.set(cacheKey, promise);
70
+ return promise;
71
+ //
72
+ async function onMiss() {
73
+ try {
74
+ const value = await originalFn.apply(ctx, args);
75
+ // Save the value in the Cache, in parallel,
76
+ // not to slow down the main function execution
77
+ // and not to fail on possible cache issues
78
+ void (async () => {
79
+ try {
80
+ await cache.set(cacheKey, value);
81
+ }
82
+ catch (err) {
83
+ logger.error({ err }); // log and ignore the error
84
+ }
85
+ finally {
86
+ // Clear the "in-flight" promise cache entry, as we now have a "permanent" cache entry
87
+ promiseCache.delete(cacheKey);
88
+ // console.log('cache set and cleared', promiseCache!.size)
89
+ }
90
+ })();
91
+ return value;
92
+ }
93
+ catch (err) {
94
+ promiseCache.delete(cacheKey);
95
+ throw err;
96
+ }
95
97
  }
96
- }
98
+ };
99
+ _objectAssign(descriptor.value, {
100
+ clear: async () => {
101
+ logger.log(`${methodSignature} @_AsyncMemo.clear()`);
102
+ await Promise.all(Array.from(instanceCache.values(), c => c.clear()));
103
+ instanceCache.clear();
104
+ },
105
+ getInstanceCache: () => instanceCache,
106
+ getCache: instance => instanceCache.get(instance),
107
+ });
108
+ return descriptor;
97
109
  };
98
- _objectAssign(descriptor.value, {
99
- clear: async () => {
100
- logger.log(`${methodSignature} @_AsyncMemo.clear()`);
101
- await Promise.all(Array.from(instanceCache.values(), c => c.clear()));
102
- instanceCache.clear();
103
- },
104
- getInstanceCache: () => instanceCache,
105
- getCache: instance => instanceCache.get(instance),
106
- });
107
- return descriptor;
108
- };
110
+ }
109
111
  /**
110
112
  Call it on a method that is decorated with `@_AsyncMemo` to get access to additional functions,
111
113
  e.g `clear` to clear the cache, or get its underlying data.
@@ -51,7 +51,7 @@ export interface MemoInstance {
51
51
  * http://inlehmansterms.net/2015/03/01/javascript-memoization/
52
52
  * https://community.risingstack.com/the-worlds-fastest-javascript-memoization-library/
53
53
  */
54
- export declare const _Memo: <FN>(opt?: MemoOptions<FN>) => MethodDecorator<FN>;
54
+ export declare function _Memo<FN>(opt?: MemoOptions<FN>): MethodDecorator<FN>;
55
55
  /**
56
56
  Call it on a method that is decorated with `@_Memo` to get access to additional functions,
57
57
  e.g `clear` to clear the cache, or get its underlying data.
@@ -28,67 +28,69 @@ import { jsonMemoSerializer, MapMemoCache } from './memo.util.js';
28
28
  * http://inlehmansterms.net/2015/03/01/javascript-memoization/
29
29
  * https://community.risingstack.com/the-worlds-fastest-javascript-memoization-library/
30
30
  */
31
- export const _Memo = (opt = {}) => (target, key, descriptor) => {
32
- _assertTypeOf(descriptor.value, 'function', 'Memoization can be applied only to methods');
33
- const originalFn = descriptor.value;
34
- // Map<ctx => MemoCache<cacheKey, result>>
35
- //
36
- // Internal map is from cacheKey to result
37
- // External map (instanceCache) is from ctx (instance of class) to Internal map
38
- // External map is Weak to not cause memory leaks, to allow ctx objects to be garbage collected
39
- // UPD: tests show that normal Map also doesn't leak (to be tested further)
40
- // Normal Map is needed to allow .clear()
41
- const instanceCache = new Map();
42
- const { logger = consoleLogger, cacheFactory = () => new MapMemoCache(), cacheKeyFn = jsonMemoSerializer, } = opt;
43
- const keyStr = String(key);
44
- const methodSignature = _getTargetMethodSignature(target, keyStr);
45
- descriptor.value = function (...args) {
46
- const ctx = this;
47
- const cacheKey = cacheKeyFn(args);
48
- let cache = instanceCache.get(ctx);
49
- if (!cache) {
50
- cache = cacheFactory();
51
- instanceCache.set(ctx, cache);
52
- }
53
- if (cache.has(cacheKey)) {
54
- // Hit
55
- return cache.get(cacheKey);
56
- }
57
- // Miss
58
- const value = originalFn.apply(ctx, args);
59
- try {
60
- cache.set(cacheKey, value);
61
- }
62
- catch (err) {
63
- logger.error({ err });
64
- }
65
- if (value instanceof Promise) {
66
- // Don't cache a rejection: evict it, so the next call retries the method.
67
- // The derived Promise is handled, so it adds no unhandled rejection.
68
- value.catch(() => {
69
- try {
70
- // Only if the key still holds this very Promise (and not a newer one, cached after an eviction)
71
- if (cache.get(cacheKey) === value)
72
- cache.delete(cacheKey);
73
- }
74
- catch (err) {
75
- logger.error({ err });
76
- }
77
- });
78
- }
79
- return value;
31
+ export function _Memo(opt = {}) {
32
+ return (target, key, descriptor) => {
33
+ _assertTypeOf(descriptor.value, 'function', 'Memoization can be applied only to methods');
34
+ const originalFn = descriptor.value;
35
+ // Map<ctx => MemoCache<cacheKey, result>>
36
+ //
37
+ // Internal map is from cacheKey to result
38
+ // External map (instanceCache) is from ctx (instance of class) to Internal map
39
+ // External map is Weak to not cause memory leaks, to allow ctx objects to be garbage collected
40
+ // UPD: tests show that normal Map also doesn't leak (to be tested further)
41
+ // Normal Map is needed to allow .clear()
42
+ const instanceCache = new Map();
43
+ const { logger = consoleLogger, cacheFactory = () => new MapMemoCache(), cacheKeyFn = jsonMemoSerializer, } = opt;
44
+ const keyStr = String(key);
45
+ const methodSignature = _getTargetMethodSignature(target, keyStr);
46
+ descriptor.value = function (...args) {
47
+ const ctx = this;
48
+ const cacheKey = cacheKeyFn(args);
49
+ let cache = instanceCache.get(ctx);
50
+ if (!cache) {
51
+ cache = cacheFactory();
52
+ instanceCache.set(ctx, cache);
53
+ }
54
+ if (cache.has(cacheKey)) {
55
+ // Hit
56
+ return cache.get(cacheKey);
57
+ }
58
+ // Miss
59
+ const value = originalFn.apply(ctx, args);
60
+ try {
61
+ cache.set(cacheKey, value);
62
+ }
63
+ catch (err) {
64
+ logger.error({ err });
65
+ }
66
+ if (value instanceof Promise) {
67
+ // Don't cache a rejection: evict it, so the next call retries the method.
68
+ // The derived Promise is handled, so it adds no unhandled rejection.
69
+ value.catch(() => {
70
+ try {
71
+ // Only if the key still holds this very Promise (and not a newer one, cached after an eviction)
72
+ if (cache.get(cacheKey) === value)
73
+ cache.delete(cacheKey);
74
+ }
75
+ catch (err) {
76
+ logger.error({ err });
77
+ }
78
+ });
79
+ }
80
+ return value;
81
+ };
82
+ _objectAssign(descriptor.value, {
83
+ clear: () => {
84
+ logger.log(`${methodSignature} @_Memo.clear()`);
85
+ instanceCache.forEach(memoCache => memoCache.clear());
86
+ instanceCache.clear();
87
+ },
88
+ getInstanceCache: () => instanceCache,
89
+ getCache: instance => instanceCache.get(instance),
90
+ });
91
+ return descriptor;
80
92
  };
81
- _objectAssign(descriptor.value, {
82
- clear: () => {
83
- logger.log(`${methodSignature} @_Memo.clear()`);
84
- instanceCache.forEach(memoCache => memoCache.clear());
85
- instanceCache.clear();
86
- },
87
- getInstanceCache: () => instanceCache,
88
- getCache: instance => instanceCache.get(instance),
89
- });
90
- return descriptor;
91
- };
93
+ }
92
94
  /**
93
95
  Call it on a method that is decorated with `@_Memo` to get access to additional functions,
94
96
  e.g `clear` to clear the cache, or get its underlying data.
@@ -10,4 +10,4 @@ export interface MemoOpts {
10
10
  *
11
11
  * Supports dropping it's cache by calling .dropCache() method of decorated function (useful in unit testing).
12
12
  */
13
- export declare const memoSimple: (opt?: MemoOpts) => MethodDecorator;
13
+ export declare function memoSimple(opt?: MemoOpts): MethodDecorator;
@@ -21,42 +21,44 @@ import { jsonMemoSerializer, MapMemoCache } from './memo.util.js';
21
21
  *
22
22
  * Supports dropping it's cache by calling .dropCache() method of decorated function (useful in unit testing).
23
23
  */
24
- export const memoSimple = (opt = {}) => (target, key, descriptor) => {
25
- if (typeof descriptor.value !== 'function') {
26
- throw new TypeError('Memoization can be applied only to methods');
27
- }
28
- const originalFn = descriptor.value;
29
- // console.log(`${key} len: ${originalFn.length}`)
30
- // todo: optimization disabled until "default arg value" use case is solved (see memo.decorator.test.ts)
31
- /*
32
- let cache: MemoCache
33
-
34
- // Function with 0 arguments
35
- if (!originalFn.length) {
36
- cache = new SingleValueMemoCache()
37
- } else {
38
- // Function with > 0 arguments
39
- cache = new MapMemoCache()
40
- // cache = new ObjectMemoCache()
41
- }
42
- */
43
- const cache = new MapMemoCache();
44
- const { logger = consoleLogger } = opt;
45
- const keyStr = String(key);
46
- const methodSignature = _getTargetMethodSignature(target, keyStr);
47
- descriptor.value = function (...args) {
48
- const ctx = this;
49
- const cacheKey = jsonMemoSerializer(args);
50
- if (cache.has(cacheKey)) {
51
- return cache.get(cacheKey);
24
+ export function memoSimple(opt = {}) {
25
+ return (target, key, descriptor) => {
26
+ if (typeof descriptor.value !== 'function') {
27
+ throw new TypeError('Memoization can be applied only to methods');
52
28
  }
53
- const res = originalFn.apply(ctx, args);
54
- cache.set(cacheKey, res);
55
- return res;
56
- };
57
- descriptor.value.dropCache = () => {
58
- logger.log(`${methodSignature} @memo.dropCache()`);
59
- cache.clear();
29
+ const originalFn = descriptor.value;
30
+ // console.log(`${key} len: ${originalFn.length}`)
31
+ // todo: optimization disabled until "default arg value" use case is solved (see memo.decorator.test.ts)
32
+ /*
33
+ let cache: MemoCache
34
+
35
+ // Function with 0 arguments
36
+ if (!originalFn.length) {
37
+ cache = new SingleValueMemoCache()
38
+ } else {
39
+ // Function with > 0 arguments
40
+ cache = new MapMemoCache()
41
+ // cache = new ObjectMemoCache()
42
+ }
43
+ */
44
+ const cache = new MapMemoCache();
45
+ const { logger = consoleLogger } = opt;
46
+ const keyStr = String(key);
47
+ const methodSignature = _getTargetMethodSignature(target, keyStr);
48
+ descriptor.value = function (...args) {
49
+ const ctx = this;
50
+ const cacheKey = jsonMemoSerializer(args);
51
+ if (cache.has(cacheKey)) {
52
+ return cache.get(cacheKey);
53
+ }
54
+ const res = originalFn.apply(ctx, args);
55
+ cache.set(cacheKey, res);
56
+ return res;
57
+ };
58
+ descriptor.value.dropCache = () => {
59
+ logger.log(`${methodSignature} @memo.dropCache()`);
60
+ cache.clear();
61
+ };
62
+ return descriptor;
60
63
  };
61
- return descriptor;
62
- };
64
+ }
@@ -8,7 +8,7 @@ import { jsonMemoSerializer, MapMemoCache } from './memo.util.js';
8
8
  export function _memoized(fn, opt = {}) {
9
9
  const { logger = consoleLogger, cacheFactory = () => new MapMemoCache(), cacheKeyFn = jsonMemoSerializer, } = opt;
10
10
  const cache = cacheFactory();
11
- const memoizedFn = function (...args) {
11
+ function memoizedFn(...args) {
12
12
  const ctx = this;
13
13
  const cacheKey = cacheKeyFn(args);
14
14
  if (cache.has(cacheKey)) {
@@ -36,7 +36,7 @@ export function _memoized(fn, opt = {}) {
36
36
  });
37
37
  }
38
38
  return value;
39
- };
39
+ }
40
40
  Object.assign(memoizedFn, { cache });
41
41
  return memoizedFn;
42
42
  }
@@ -10,7 +10,7 @@ import { jsonMemoSerializer, MapAsyncMemoCache } from './memo.util.js';
10
10
  export function _memoizedAsync(fn, opt = {}) {
11
11
  const { logger = consoleLogger, cacheFactory = () => new MapAsyncMemoCache(), cacheKeyFn = jsonMemoSerializer, } = opt;
12
12
  const cache = cacheFactory();
13
- const memoizedFn = async function (...args) {
13
+ async function memoizedFn(...args) {
14
14
  const ctx = this;
15
15
  const cacheKey = cacheKeyFn(args);
16
16
  // MISS, so that a failed cache `get` is a miss too (and not a cached `undefined`)
@@ -34,7 +34,7 @@ export function _memoizedAsync(fn, opt = {}) {
34
34
  }
35
35
  })();
36
36
  return value;
37
- };
37
+ }
38
38
  Object.assign(memoizedFn, { cache });
39
39
  return memoizedFn;
40
40
  }
@@ -6,4 +6,4 @@
6
6
  * Does not support `cacheKey`.
7
7
  * So, the same Promise is returned, regardless of the arguments.
8
8
  */
9
- export declare const _SwarmSafe: () => MethodDecorator;
9
+ export declare function _SwarmSafe(): MethodDecorator;