Skip to content

Commit

Permalink
feat(esl-utils): utility to postpone execution to microtask
Browse files Browse the repository at this point in the history
  • Loading branch information
ala-n committed May 30, 2023
1 parent 68d0556 commit 4f4f637
Show file tree
Hide file tree
Showing 3 changed files with 42 additions and 0 deletions.
1 change: 1 addition & 0 deletions src/modules/esl-utils/async.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,4 +3,5 @@ export * from './async/promise';
export * from './async/raf';
export * from './async/debounce';
export * from './async/throttle';
export * from './async/microtask';
export * from './async/delayed-task';
15 changes: 15 additions & 0 deletions src/modules/esl-utils/async/microtask.ts
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);
});
};
}
26 changes: 26 additions & 0 deletions src/modules/esl-utils/async/test/microtask.test.ts
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));
});
});

0 comments on commit 4f4f637

Please # to comment.