-
Notifications
You must be signed in to change notification settings - Fork 530
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
feat(utils): implement defer (#3882)
- Loading branch information
Showing
3 changed files
with
74 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,54 @@ | ||
import defer from '../defer'; | ||
|
||
describe('defer', () => { | ||
it('defers the call to the function', async () => { | ||
const fn = jest.fn(); | ||
const deferred = defer(fn); | ||
|
||
deferred(); | ||
|
||
expect(fn).toHaveBeenCalledTimes(0); | ||
|
||
await Promise.resolve(); | ||
|
||
expect(fn).toHaveBeenCalledTimes(1); | ||
}); | ||
|
||
it('deduplicates the calls to the function', async () => { | ||
const fn = jest.fn(); | ||
const deferred = defer(fn); | ||
|
||
deferred(); | ||
deferred(); | ||
deferred(); | ||
|
||
expect(fn).toHaveBeenCalledTimes(0); | ||
|
||
await Promise.resolve(); | ||
|
||
expect(fn).toHaveBeenCalledTimes(1); | ||
}); | ||
|
||
it('deduplicates the calls only until the next microtask', async () => { | ||
const fn = jest.fn(); | ||
const deferred = defer(fn); | ||
|
||
deferred(); | ||
deferred(); | ||
deferred(); | ||
|
||
expect(fn).toHaveBeenCalledTimes(0); | ||
|
||
await Promise.resolve(); | ||
|
||
expect(fn).toHaveBeenCalledTimes(1); | ||
|
||
deferred(); | ||
deferred(); | ||
deferred(); | ||
|
||
await Promise.resolve(); | ||
|
||
expect(fn).toHaveBeenCalledTimes(2); | ||
}); | ||
}); |
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,19 @@ | ||
const nextMicroTask = Promise.resolve(); | ||
|
||
type Callback = (...args: any[]) => void; | ||
|
||
const defer = (callback: Callback): Callback => { | ||
let progress: Promise<void> | null = null; | ||
return (...args) => { | ||
if (progress !== null) { | ||
return; | ||
} | ||
|
||
progress = nextMicroTask.then(() => { | ||
callback(...args); | ||
progress = null; | ||
}); | ||
}; | ||
}; | ||
|
||
export default defer; |
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