Skip to content

Commit

Permalink
fix(microtask): fix argument list on next fn call
Browse files Browse the repository at this point in the history
  • Loading branch information
nattallius committed Jan 25, 2024
1 parent 39e7dca commit f421e88
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 5 deletions.
3 changes: 2 additions & 1 deletion src/modules/esl-utils/async/microtask.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,13 +3,14 @@
* (as a microtask produced with Promise)
*/
export function microtask<T>(fn: (...arg: [T?]) => void, thisArg?: object): (arg?: T) => void {
const args: T[] = [];
let 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);
args = [];
});
};
}
13 changes: 9 additions & 4 deletions src/modules/esl-utils/async/test/microtask.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,13 +14,18 @@ describe('sync/microtask', () => {
await Promise.resolve();
expect(fn).toBeCalledTimes(1);
});
test('Decorated as microtask callback receives a list of call arguments', async () => {
test('Decorated as microtask callback receives a correct list of call arguments', async () => {
const fn = jest.fn();
const decorated = microtask(fn);
const params = [Symbol('Arg 1'), Symbol('Arg 2'), Symbol('Arg 3')];
const params1 = [Symbol('Arg 1'), Symbol('Arg 2'), Symbol('Arg 3')];

for (const param of params) decorated(param);
for (const param of params1) decorated(param);
await Promise.resolve();
expect(fn).toBeCalledWith(expect.arrayContaining(params));
expect(fn).toBeCalledWith(params1);

const params2 = [Symbol('Arg 4'), Symbol('Arg 5')];
for (const param of params2) decorated(param);
await Promise.resolve();
expect(fn).lastCalledWith(params2);
});
});

0 comments on commit f421e88

Please sign in to comment.