-
Notifications
You must be signed in to change notification settings - Fork 0
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
1 parent
dd65532
commit d9bdc5b
Showing
3 changed files
with
63 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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1 @@ | ||
export * from './lazy/index.js' |
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,17 @@ | ||
/** | ||
* A lazy function for typescript projects. | ||
*/ | ||
export const lazy = <T>(create: () => T) => { | ||
let instance: T | undefined = undefined | ||
return (): T => instance ??= create() | ||
} | ||
|
||
/* | ||
* Example: | ||
* const config = lazy( | ||
* () => fs.readFileSync('config.json').then(f => cfgSchema.parse(f)) | ||
* ) | ||
* | ||
* config().PROP_1 | ||
* config().PROP_2 // config file is read and parsed only once | ||
*/ |
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,45 @@ | ||
import { expect, test } from 'vitest' | ||
import { lazy } from './index.js' | ||
|
||
test('lazy remembers the value of its function', () => { | ||
const lazyValue = lazy(() => 1) | ||
|
||
expect(lazyValue()).toBe(1) | ||
}) | ||
|
||
test('lazy executes its function only once', () => { | ||
let countExecutions = 0 | ||
|
||
const lazyValue = lazy(() => { | ||
countExecutions++ | ||
return 1 | ||
}) | ||
|
||
lazyValue() | ||
lazyValue() | ||
|
||
expect(countExecutions).toBe(1) | ||
}) | ||
|
||
test('lazy does propagate exceptions on first use', () => { | ||
const lazyValue = lazy(() => { | ||
throw new Error() | ||
}) | ||
|
||
expect(lazyValue).toThrowError() | ||
}) | ||
|
||
test('lazy retries on exceptions', () => { | ||
let countExecutions = 0 | ||
|
||
const lazyValue = lazy(() => { | ||
if (countExecutions === 0) { | ||
countExecutions++ | ||
throw new Error() | ||
} | ||
return 1 | ||
}) | ||
|
||
expect(lazyValue).toThrowError() | ||
expect(lazyValue()).toBe(1) | ||
}) |