Skip to content

Commit

Permalink
feat: 'throttle' API changes
Browse files Browse the repository at this point in the history
make promise creation lazy

decorated method no longer returne Promise use 'throttleMethod.promise' instead
  • Loading branch information
Anna-MariiaPetryk committed Aug 18, 2021
1 parent e5f2cd3 commit 8db7bfb
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 11 deletions.
21 changes: 12 additions & 9 deletions src/modules/esl-utils/async/test/throttle.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,14 +9,14 @@ describe('async/throttle', () => {
const fn = jest.fn();
const throttled = throttle(fn, 100);

expect(throttled()).toBeInstanceOf(Promise);
expect(throttled()).toBeUndefined();
expect(fn).toBeCalledTimes(1);
jest.advanceTimersByTime(50)
expect(throttled()).toBeInstanceOf(Promise);
jest.advanceTimersByTime(50);
expect(throttled()).toBeUndefined();
expect(fn).toBeCalledTimes(1);
jest.advanceTimersByTime(100)
expect(fn).toBeCalledTimes(2);
expect(throttled()).toBeInstanceOf(Promise);
expect(throttled()).toBeUndefined();
expect(fn).toBeCalledTimes(3);
});

Expand All @@ -25,18 +25,21 @@ describe('async/throttle', () => {
const throttled = throttle(fn, 0);

const context = {};
return throttled.call(context).then((val: any) => expect(val).toBe(context));
}, 50);
throttled.call(context);
const promise$ = throttled.promise;
jest.runAllTimers();
return expect(promise$).resolves.toBe(context);
});

test('test deferred result', () => {
const fn = jest.fn((n) => n + 1);
const throttled = throttle(fn as (n: number) => number, 50);

expect(throttled.promise).toBeInstanceOf(Promise);
expect(throttled(1)).toBeInstanceOf(Promise);
expect(throttled(2)).toBe(throttled.promise);
expect(throttled(1)).toBeUndefined();
expect(throttled(2)).toBeUndefined();
expect(throttled.promise).toBeInstanceOf(Promise);
expect(throttled(4)).toBeInstanceOf(Promise);
expect(throttled(4)).toBeUndefined();;

expect(fn).toBeCalledTimes(1);
expect(fn).lastCalledWith(1);
Expand Down
3 changes: 1 addition & 2 deletions src/modules/esl-utils/async/throttle.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ export function throttle<F extends AnyToAnyFnSignature>(fn: F, threshold = 250):

if (!last || now >= last + threshold) {
last = now;
return Promise.resolve(fn.apply(this, args));
fn.apply(this, args);
}

deferred = deferred || createDeferred();
Expand All @@ -37,7 +37,6 @@ export function throttle<F extends AnyToAnyFnSignature>(fn: F, threshold = 250):
deferred!.resolve(fn.apply(this, args));
deferred = null;
}, threshold);
return deferred.promise;
}
Object.defineProperty(throttledSubject, 'promise', {
get: () => deferred ? deferred.promise : Promise.resolve()
Expand Down

0 comments on commit 8db7bfb

Please sign in to comment.