Skip to content

Commit

Permalink
feat(utils): implement defer (#3882)
Browse files Browse the repository at this point in the history
  • Loading branch information
samouss authored and Haroenv committed Oct 23, 2019
1 parent 75ad673 commit 8af470e
Show file tree
Hide file tree
Showing 3 changed files with 74 additions and 0 deletions.
54 changes: 54 additions & 0 deletions src/lib/utils/__tests__/defer.ts
@@ -0,0 +1,54 @@
import defer from '../defer';

describe('defer', () => {
it('defers the call to the function', async () => {
const fn = jest.fn();
const deferred = defer(fn);

deferred();

expect(fn).toHaveBeenCalledTimes(0);

await Promise.resolve();

expect(fn).toHaveBeenCalledTimes(1);
});

it('deduplicates the calls to the function', async () => {
const fn = jest.fn();
const deferred = defer(fn);

deferred();
deferred();
deferred();

expect(fn).toHaveBeenCalledTimes(0);

await Promise.resolve();

expect(fn).toHaveBeenCalledTimes(1);
});

it('deduplicates the calls only until the next microtask', async () => {
const fn = jest.fn();
const deferred = defer(fn);

deferred();
deferred();
deferred();

expect(fn).toHaveBeenCalledTimes(0);

await Promise.resolve();

expect(fn).toHaveBeenCalledTimes(1);

deferred();
deferred();
deferred();

await Promise.resolve();

expect(fn).toHaveBeenCalledTimes(2);
});
});
19 changes: 19 additions & 0 deletions src/lib/utils/defer.ts
@@ -0,0 +1,19 @@
const nextMicroTask = Promise.resolve();

type Callback = (...args: any[]) => void;

const defer = (callback: Callback): Callback => {
let progress: Promise<void> | null = null;
return (...args) => {
if (progress !== null) {
return;
}

progress = nextMicroTask.then(() => {
callback(...args);
progress = null;
});
};
};

export default defer;
1 change: 1 addition & 0 deletions src/lib/utils/index.ts
@@ -1,4 +1,5 @@
export { default as capitalize } from './capitalize';
export { default as defer } from './defer';
export { default as isDomElement } from './isDomElement';
export { default as getContainerNode } from './getContainerNode';
export { default as isSpecialClick } from './isSpecialClick';
Expand Down

0 comments on commit 8af470e

Please sign in to comment.