-
Notifications
You must be signed in to change notification settings - Fork 8
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
feat(esl-utils): utility to postpone execution to microtask
- Loading branch information
Showing
3 changed files
with
42 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,15 @@ | ||
/** | ||
* A decorator utility to postpone callback execution once after the main task execution | ||
* (as a microtask produced with Promise) | ||
*/ | ||
export function microtask<T>(fn: (...arg: [T?]) => void, thisArg?: object): (arg?: T) => void { | ||
const args: T[] = []; | ||
return function microtaskFn(arg: T): void { | ||
args.push(arg); | ||
if ((microtaskFn as any).request) return; | ||
(microtaskFn as any).request = Promise.resolve().then(() => { | ||
delete (microtaskFn as any).request; | ||
fn.call(thisArg || this, args); | ||
}); | ||
}; | ||
} |
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,26 @@ | ||
import {microtask} from '../microtask'; | ||
|
||
describe('sync/microtask', () => { | ||
test('Decorated as microtask callback call does not lead to original function immediate execution', () => { | ||
const fn = jest.fn(); | ||
const decorated = microtask(fn); | ||
for (let i = 0; i < 5; i++) decorated(); | ||
expect(fn).toBeCalledTimes(0); | ||
}); | ||
test('Decorated as microtask callback called once the macrotask done', async () => { | ||
const fn = jest.fn(); | ||
const decorated = microtask(fn); | ||
for (let i = 0; i < 5; i++) decorated(); | ||
await Promise.resolve(); | ||
expect(fn).toBeCalledTimes(1); | ||
}); | ||
test('Decorated as microtask callback receives a list of call arguments', async () => { | ||
const fn = jest.fn(); | ||
const decorated = microtask(fn); | ||
const params = [Symbol('Arg 1'), Symbol('Arg 2'), Symbol('Arg 3')]; | ||
|
||
for (const param of params) decorated(param); | ||
await Promise.resolve(); | ||
expect(fn).toBeCalledWith(expect.arrayContaining(params)); | ||
}); | ||
}); |