Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix(microtask): fix argument list on next fn call #2195

Merged
merged 2 commits into from
Jan 26, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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 = [];
});
};
}
12 changes: 12 additions & 0 deletions src/modules/esl-utils/async/test/microtask.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,4 +23,16 @@ describe('sync/microtask', () => {
await Promise.resolve();
expect(fn).toBeCalledWith(expect.arrayContaining(params));
});
test('Decorated as microtask callback refreshes after decorated method call (leak protected)', async () => {
const fn = jest.fn();
const decorated = microtask(fn);
const params1 = [Symbol('Arg 1'), Symbol('Arg 2')];
for (const param of params1) decorated(param);
await Promise.resolve();

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