Skip to content

Commit a88b6c8

Browse files
committed
feat(utils): Add LazyKeyed.wrap
1 parent b427963 commit a88b6c8

File tree

3 files changed

+24
-4
lines changed

3 files changed

+24
-4
lines changed

.changeset/brown-canyons-pull.md

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
---
2+
'@inox-tools/utils': patch
3+
---
4+
5+
Add `LazyKeyed.wrap` to be simmetric to `Lazy.wrap`.

.changeset/grumpy-years-beam.md

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
---
2+
'@inox-tools/utils': patch
3+
---
4+
5+
Declare static constructors of `Lazy` and `LazyKeyed` to take `this: void` so typescript strictest modes allow passing those functions as values without rebinding.

packages/utils/src/lazy.ts

Lines changed: 14 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -53,7 +53,7 @@ export class Lazy<T> implements Promise<T> {
5353
* @param factory - A function that produces the value when first accessed
5454
* @returns A new Lazy instance wrapping the factory
5555
*/
56-
public static of<T>(factory: () => T): Lazy<T> {
56+
public static of<T>(this: void, factory: () => T): Lazy<T> {
5757
return new Lazy(factory);
5858
}
5959

@@ -62,7 +62,7 @@ export class Lazy<T> implements Promise<T> {
6262
*
6363
* The function will at most be called once, on the first use of the value.
6464
*/
65-
public static wrap<T>(factory: () => T): () => T {
65+
public static wrap<T>(this: void, factory: () => T): (this: void) => T {
6666
const lazy = Lazy.of(factory);
6767
return lazy.get.bind(lazy);
6868
}
@@ -271,8 +271,18 @@ export class LazyKeyed<T> {
271271
* @param factory - A function that produces a value for a given key
272272
* @returns A new LazyKeyed instance
273273
*/
274-
public static of<T>(factory: (key: string) => T): LazyKeyed<T> {
275-
return new this(factory);
274+
public static of<T>(this: void, factory: (key: string) => T): LazyKeyed<T> {
275+
return new LazyKeyed(factory);
276+
}
277+
278+
/**
279+
* Wrap the given factory into a lazily computed memoized value.
280+
*
281+
* The function will at most be called once per given key, on the first use of said key.
282+
*/
283+
public static wrap<T>(this: void, factory: (key: string) => T): (this: void, key: string) => T {
284+
const keyed = LazyKeyed.of(factory);
285+
return keyed.get.bind(keyed);
276286
}
277287

278288
/**

0 commit comments

Comments
 (0)