fix throttle function not being able to run with argument(s)
This commit is contained in:
@@ -1,20 +1,10 @@
|
|||||||
export function throttle<T extends []>(
|
export type CallbackType = (..._: any[]) => void;
|
||||||
callback: (..._: T) => void, wait: number,
|
|
||||||
timer: ITimer = NodeTimer): (..._: T) => void {
|
export function throttle(
|
||||||
let queuedToRun: ReturnType<typeof setTimeout>;
|
callback: CallbackType, waitInMs: number,
|
||||||
let previouslyRun: number;
|
timer: ITimer = NodeTimer): CallbackType {
|
||||||
return function invokeFn(...args: T) {
|
const throttler = new Throttler(timer, waitInMs, callback);
|
||||||
const now = timer.dateNow();
|
return (...args: any[]) => throttler.invoke(...args);
|
||||||
if (queuedToRun) {
|
|
||||||
queuedToRun = timer.clearTimeout(queuedToRun) as undefined;
|
|
||||||
}
|
|
||||||
if (!previouslyRun || (now - previouslyRun >= wait)) {
|
|
||||||
callback(...args);
|
|
||||||
previouslyRun = now;
|
|
||||||
} else {
|
|
||||||
queuedToRun = timer.setTimeout(invokeFn.bind(null, ...args), wait - (now - previouslyRun));
|
|
||||||
}
|
|
||||||
};
|
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface ITimer {
|
export interface ITimer {
|
||||||
@@ -28,3 +18,35 @@ const NodeTimer: ITimer = {
|
|||||||
clearTimeout: (timeoutId) => clearTimeout(timeoutId),
|
clearTimeout: (timeoutId) => clearTimeout(timeoutId),
|
||||||
dateNow: () => Date.now(),
|
dateNow: () => Date.now(),
|
||||||
};
|
};
|
||||||
|
|
||||||
|
interface IThrottler {
|
||||||
|
invoke: CallbackType;
|
||||||
|
}
|
||||||
|
|
||||||
|
class Throttler implements IThrottler {
|
||||||
|
private queuedToRun: ReturnType<typeof setTimeout>;
|
||||||
|
private previouslyRun: number;
|
||||||
|
constructor(
|
||||||
|
private readonly timer: ITimer,
|
||||||
|
private readonly waitInMs: number,
|
||||||
|
private readonly callback: CallbackType) {
|
||||||
|
if (!timer) { throw new Error('undefined timer'); }
|
||||||
|
if (!waitInMs) { throw new Error('no delay to throttle'); }
|
||||||
|
if (waitInMs < 0) { throw new Error('negative delay'); }
|
||||||
|
if (!callback) { throw new Error('undefined callback'); }
|
||||||
|
}
|
||||||
|
public invoke(...args: any[]): void {
|
||||||
|
const now = this.timer.dateNow();
|
||||||
|
if (this.queuedToRun) {
|
||||||
|
this.queuedToRun = this.timer.clearTimeout(this.queuedToRun) as undefined;
|
||||||
|
}
|
||||||
|
if (!this.previouslyRun || (now - this.previouslyRun >= this.waitInMs)) {
|
||||||
|
this.callback(...args);
|
||||||
|
this.previouslyRun = now;
|
||||||
|
} else {
|
||||||
|
const nextCall = () => this.invoke(...args);
|
||||||
|
const nextCallDelayInMs = this.waitInMs - (now - this.previouslyRun);
|
||||||
|
this.queuedToRun = this.timer.setTimeout(nextCall, nextCallDelayInMs);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|||||||
@@ -5,6 +5,32 @@ import { EventSource } from '@/infrastructure/Events/EventSource';
|
|||||||
import { IEventSubscription } from '@/infrastructure/Events/IEventSource';
|
import { IEventSubscription } from '@/infrastructure/Events/IEventSource';
|
||||||
|
|
||||||
describe('throttle', () => {
|
describe('throttle', () => {
|
||||||
|
it('throws if callback is undefined', () => {
|
||||||
|
// arrange
|
||||||
|
const expectedError = 'undefined callback';
|
||||||
|
const callback = undefined;
|
||||||
|
// act
|
||||||
|
const act = () => throttle(callback, 500);
|
||||||
|
// assert
|
||||||
|
expect(act).to.throw(expectedError);
|
||||||
|
});
|
||||||
|
describe('throws if waitInMs is negative or zero', () => {
|
||||||
|
// arrange
|
||||||
|
const testCases = [
|
||||||
|
{ value: 0, expectedError: 'no delay to throttle' },
|
||||||
|
{ value: -2, expectedError: 'negative delay' },
|
||||||
|
];
|
||||||
|
const callback = () => { return; };
|
||||||
|
for (const testCase of testCases) {
|
||||||
|
it(`"${testCase.value}" throws "${testCase.expectedError}"`, () => {
|
||||||
|
// act
|
||||||
|
const waitInMs = testCase.value;
|
||||||
|
const act = () => throttle(callback, waitInMs);
|
||||||
|
// assert
|
||||||
|
expect(act).to.throw(testCase.expectedError);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
});
|
||||||
it('should call the callback immediately', () => {
|
it('should call the callback immediately', () => {
|
||||||
// arrange
|
// arrange
|
||||||
const timer = new TimerMock();
|
const timer = new TimerMock();
|
||||||
@@ -21,16 +47,17 @@ describe('throttle', () => {
|
|||||||
const timer = new TimerMock();
|
const timer = new TimerMock();
|
||||||
let totalRuns = 0;
|
let totalRuns = 0;
|
||||||
const callback = () => totalRuns++;
|
const callback = () => totalRuns++;
|
||||||
const throttleFunc = throttle(callback, 500, timer);
|
const waitInMs = 500;
|
||||||
|
const throttleFunc = throttle(callback, waitInMs, timer);
|
||||||
// act
|
// act
|
||||||
throttleFunc();
|
throttleFunc();
|
||||||
totalRuns--;
|
totalRuns--; // So we don't count the initial run
|
||||||
throttleFunc();
|
throttleFunc();
|
||||||
timer.tick(500);
|
timer.tickNext(waitInMs);
|
||||||
// assert
|
// assert
|
||||||
expect(totalRuns).to.equal(1);
|
expect(totalRuns).to.equal(1);
|
||||||
});
|
});
|
||||||
it('calls the callback at most once at given time', () => {
|
it('should call the callback at most once at given time', () => {
|
||||||
// arrange
|
// arrange
|
||||||
const timer = new TimerMock();
|
const timer = new TimerMock();
|
||||||
let totalRuns = 0;
|
let totalRuns = 0;
|
||||||
@@ -40,11 +67,43 @@ describe('throttle', () => {
|
|||||||
const throttleFunc = throttle(callback, waitInMs, timer);
|
const throttleFunc = throttle(callback, waitInMs, timer);
|
||||||
// act
|
// act
|
||||||
for (let i = 0; i < totalCalls; i++) {
|
for (let i = 0; i < totalCalls; i++) {
|
||||||
timer.tick(waitInMs / totalCalls * i);
|
timer.setCurrentTime(waitInMs / totalCalls * i);
|
||||||
throttleFunc();
|
throttleFunc();
|
||||||
}
|
}
|
||||||
// assert
|
// assert
|
||||||
expect(totalRuns).to.equal(2); // initial and at the end
|
expect(totalRuns).to.equal(2); // one initial and one at the end
|
||||||
|
});
|
||||||
|
it('should call the callback as long as delay is waited', () => {
|
||||||
|
// arrange
|
||||||
|
const timer = new TimerMock();
|
||||||
|
let totalRuns = 0;
|
||||||
|
const callback = () => totalRuns++;
|
||||||
|
const waitInMs = 500;
|
||||||
|
const expectedTotalRuns = 10;
|
||||||
|
const throttleFunc = throttle(callback, waitInMs, timer);
|
||||||
|
// act
|
||||||
|
for (let i = 0; i < expectedTotalRuns; i++) {
|
||||||
|
throttleFunc();
|
||||||
|
timer.tickNext(waitInMs);
|
||||||
|
}
|
||||||
|
// assert
|
||||||
|
expect(totalRuns).to.equal(expectedTotalRuns);
|
||||||
|
});
|
||||||
|
it('should call arguments as expected', () => {
|
||||||
|
// arrange
|
||||||
|
const timer = new TimerMock();
|
||||||
|
const expected = [ 1, 2, 3 ];
|
||||||
|
const actual = new Array<number>();
|
||||||
|
const callback = (arg: number) => { actual.push(arg); };
|
||||||
|
const waitInMs = 500;
|
||||||
|
const throttleFunc = throttle(callback, waitInMs, timer);
|
||||||
|
// act
|
||||||
|
for (const arg of expected) {
|
||||||
|
throttleFunc(arg);
|
||||||
|
timer.tickNext(waitInMs);
|
||||||
|
}
|
||||||
|
// assert
|
||||||
|
expect(expected).to.deep.equal(actual);
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -69,7 +128,10 @@ class TimerMock implements ITimer {
|
|||||||
public dateNow(): number {
|
public dateNow(): number {
|
||||||
return this.currentTime;
|
return this.currentTime;
|
||||||
}
|
}
|
||||||
public tick(ms: number): void {
|
public tickNext(ms: number): void {
|
||||||
|
this.setCurrentTime(this.currentTime + ms);
|
||||||
|
}
|
||||||
|
public setCurrentTime(ms: number): void {
|
||||||
this.currentTime = ms;
|
this.currentTime = ms;
|
||||||
this.timeChanged.notify(this.currentTime);
|
this.timeChanged.notify(this.currentTime);
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user