@naturalcycles/js-lib 14.55.0 → 14.58.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/src/lazy.ts ADDED
@@ -0,0 +1,73 @@
1
+ import { AnyFunction, AnyObject } from './types'
2
+
3
+ /**
4
+ * const value = lazyValue(() => expensiveComputation())
5
+ *
6
+ * value() // calls expensiveComputation() once
7
+ * value() // returns cached result
8
+ * value() // returns cached result
9
+ *
10
+ * Based on: https://github.com/sindresorhus/lazy-value
11
+ */
12
+ export function _lazyValue<T extends AnyFunction>(fn: T): T {
13
+ let isCalled = false
14
+ let result: any
15
+
16
+ return (() => {
17
+ if (!isCalled) {
18
+ isCalled = true
19
+ result = fn()
20
+ }
21
+
22
+ return result
23
+ }) as any
24
+ }
25
+
26
+ /**
27
+ * interface Obj {
28
+ * v: number
29
+ * }
30
+ *
31
+ * const obj = {} as Obj
32
+ *
33
+ * _defineLazyProperty(obj, 'v', () => expensiveComputation())
34
+ * obj.v // runs expensiveComputation() once
35
+ * obj.v // cached value
36
+ * obj.v // cached value
37
+ *
38
+ * Based on: https://github.com/sindresorhus/define-lazy-prop
39
+ */
40
+ export function _defineLazyProperty<OBJ extends AnyObject>(
41
+ obj: OBJ,
42
+ propertyName: keyof OBJ,
43
+ fn: AnyFunction,
44
+ ): OBJ {
45
+ const define = (value: any) =>
46
+ Object.defineProperty(obj, propertyName, { value, enumerable: true, writable: true })
47
+
48
+ Object.defineProperty(obj, propertyName, {
49
+ configurable: true,
50
+ enumerable: true,
51
+ get() {
52
+ const result = fn()
53
+ define(result)
54
+ return result
55
+ },
56
+ set(value) {
57
+ define(value)
58
+ },
59
+ })
60
+
61
+ return obj
62
+ }
63
+
64
+ /**
65
+ * Like _defineLazyProperty, but allows to define multiple props at once.
66
+ */
67
+ export function _defineLazyProps<OBJ extends AnyObject>(
68
+ obj: OBJ,
69
+ props: Partial<Record<keyof OBJ, AnyFunction>>,
70
+ ): OBJ {
71
+ Object.entries(props).forEach(([k, fn]) => _defineLazyProperty(obj, k, fn!))
72
+ return obj
73
+ }
@@ -23,8 +23,6 @@ export class AggregatedError<RESULT = any> extends Error {
23
23
  this.errors = mappedErrors
24
24
  this.results = results
25
25
 
26
- this.constructor = AggregatedError
27
- ;(this as any).__proto__ = AggregatedError.prototype
28
26
  Object.defineProperty(this, 'name', {
29
27
  value: this.constructor.name,
30
28
  configurable: true,
@@ -35,6 +33,7 @@ export class AggregatedError<RESULT = any> extends Error {
35
33
  } else {
36
34
  Object.defineProperty(this, 'stack', {
37
35
  value: new Error().stack, // eslint-disable-line unicorn/error-message
36
+ writable: true,
38
37
  configurable: true,
39
38
  })
40
39
  }