zwave-js
Version:
Z-Wave driver written entirely in JavaScript/TypeScript
45 lines • 1.63 kB
JavaScript
import { throttle } from "@zwave-js/shared";
/** Mixin to provide statistics functionality. Requires the base class to extend EventEmitter. */
export class StatisticsHost {
_statistics;
get statistics() {
if (!this._statistics)
this.resetStatistics();
return Object.freeze(this._statistics);
}
resetStatistics() {
this.updateStatistics(() => this.createEmpty());
}
/** Can be overridden in derived classes to specify additional args to be included in the statistics event callback. */
getAdditionalEventArgs() {
return [];
}
/** Can be overridden in derived classes to specify how to transform the internal statistics before emitting them to applications. */
transformBeforeEmit(statistics) {
// No transformation by default
return statistics;
}
_emitUpdate;
updateStatistics(updater) {
this._statistics = updater(this._statistics ?? this.createEmpty());
if (!this._emitUpdate) {
this._emitUpdate = throttle(this.emit.bind(this, "statistics updated", ...this.getAdditionalEventArgs()), 250, true);
}
this._emitUpdate(this.transformBeforeEmit(this._statistics));
}
incrementStatistics(property) {
this.updateStatistics((s) => {
const value = s[property];
if (typeof value === "number") {
return {
...s,
[property]: value + 1,
};
}
else {
return s;
}
});
}
}
//# sourceMappingURL=Statistics.js.map