Files
lik/ts/classes.timedaggregator.ts

72 lines
2.0 KiB
TypeScript
Raw Normal View History

2024-02-25 13:01:06 +01:00
import * as plugins from './classes.plugins.js';
2019-08-02 16:32:52 +02:00
export interface ITimedAggregatorOptions<T> {
aggregationIntervalInMillis: number;
functionForAggregation: (input: T[]) => void;
}
export class TimedAggregtor<T> {
public options: ITimedAggregatorOptions<T>;
private storageArray: T[] = [];
private isStopped = false;
2019-08-02 16:32:52 +02:00
constructor(optionsArg: ITimedAggregatorOptions<T>) {
this.options = optionsArg;
}
private aggregationTimer: plugins.smarttime.Timer;
2019-08-02 16:33:45 +02:00
private checkAggregationStatus() {
if (this.isStopped) {
return;
}
2019-08-02 16:32:52 +02:00
const addAggregationTimer = () => {
this.aggregationTimer = new plugins.smarttime.Timer(this.options.aggregationIntervalInMillis);
this.aggregationTimer.completed.then(() => {
if (this.isStopped) {
this.aggregationTimer = null;
return;
}
2019-08-02 16:32:52 +02:00
const aggregateForProcessing = this.storageArray;
if (aggregateForProcessing.length === 0) {
this.aggregationTimer = null;
return;
}
this.storageArray = [];
addAggregationTimer();
this.options.functionForAggregation(aggregateForProcessing);
});
this.aggregationTimer.start();
};
if (!this.aggregationTimer) {
addAggregationTimer();
}
}
public add(aggregationArg: T) {
if (this.isStopped) {
return;
}
2019-08-02 16:32:52 +02:00
this.storageArray.push(aggregationArg);
this.checkAggregationStatus();
}
/**
* stops the aggregation timer chain
* @param flushRemaining if true, calls functionForAggregation with any remaining items
*/
public stop(flushRemaining: boolean = false) {
this.isStopped = true;
if (this.aggregationTimer) {
this.aggregationTimer.reset();
this.aggregationTimer = null;
}
if (flushRemaining && this.storageArray.length > 0) {
const remaining = this.storageArray;
this.storageArray = [];
this.options.functionForAggregation(remaining);
} else {
this.storageArray = [];
}
}
2019-08-02 16:33:45 +02:00
}