Skip to content

Instantly share code, notes, and snippets.

@DimitryDushkin
Last active March 14, 2019 07:27
Show Gist options
  • Save DimitryDushkin/a5de02adebf963e770fbe93e194e30b3 to your computer and use it in GitHub Desktop.
Save DimitryDushkin/a5de02adebf963e770fbe93e194e30b3 to your computer and use it in GitHub Desktop.
Helpful wrapper to make sure that function body is working once per multiple calls
export const SINGLE_TASK_BLOCKED = Symbol('task blocked');
export type SingleTaskBlocked = typeof SINGLE_TASK_BLOCKED;
export const singleTaskQueue = <TReturn, TArgs extends Array<any>>(func: (...args: TArgs) => Promise<TReturn>) => {
let isWorking = false;
return async (...args: TArgs): Promise<TReturn | SingleTaskBlocked> => {
if (isWorking) {
return SINGLE_TASK_BLOCKED;
}
isWorking = true;
const result = await func(...args);
isWorking = false;
return result;
};
};
// Example as test
test('singleTaskQueue works as expected with heavy function', async () => {
const sumSingleTaskQueued = singleTaskQueue(async () => {
await pause(50);
return 'result';
});
const expectedResult = 'result';
const result = sumSingleTaskQueued();
const resultBlocked = sumSingleTaskQueued();
expect(await result).toEqual(expectedResult);
expect(await resultBlocked).toEqual(SINGLE_TASK_BLOCKED);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment