generated from sapphiredev/sapphire-template
-
-
Notifications
You must be signed in to change notification settings - Fork 37
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
3 changed files
with
34 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,10 @@ | ||
/** | ||
* Lazily creates a constant or load a module and caches it internally | ||
* @param cb The callback to lazily run | ||
* @returns The value returned by the callback, or the cached value if it was already initialised once. | ||
*/ | ||
export function lazy<T>(cb: () => T) { | ||
let defaultValue: T; | ||
|
||
return () => (defaultValue ??= cb()); | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,23 @@ | ||
import { lazy } from '../src'; | ||
|
||
describe('lazy', () => { | ||
test('GIVEN string callback THEN returns the same', () => { | ||
const callback = vi.fn(() => 'Lorem Ipsum'); | ||
|
||
const lazyStoredValue = lazy(callback); | ||
|
||
expect(lazyStoredValue()).toEqual('Lorem Ipsum'); | ||
}); | ||
|
||
test('GIVEN string callback with cached value THEN returns the same', () => { | ||
const callback = vi.fn(() => 'Lorem Ipsum'); | ||
|
||
const lazyStoredValue = lazy(callback); | ||
|
||
lazyStoredValue(); | ||
const cachedValue = lazyStoredValue(); | ||
|
||
expect(callback).toHaveBeenCalledOnce(); | ||
expect(cachedValue).toEqual('Lorem Ipsum'); | ||
}); | ||
}); |