From 71368511236d592cb98baa0a4ac2ce33db61793e Mon Sep 17 00:00:00 2001 From: Nick Krecklow Date: Mon, 11 May 2020 18:16:41 -0500 Subject: [PATCH] centralize shift behavior into TimeTracker func --- lib/servers.js | 14 ++------------ lib/time.js | 20 ++++++++++---------- 2 files changed, 12 insertions(+), 22 deletions(-) diff --git a/lib/servers.js b/lib/servers.js index 412983e..58e6b8d 100644 --- a/lib/servers.js +++ b/lib/servers.js @@ -26,23 +26,13 @@ class ServerRegistration { const playerCount = resp ? resp.players.online : null // Store into in-memory ping data - this._pingHistory.push(playerCount) - - // Trim pingHistory to avoid memory leaks - if (this._pingHistory.length > TimeTracker.getMaxServerGraphDataLength()) { - this._pingHistory.shift() - } + TimeTracker.pushAndShift(this._pingHistory, playerCount, TimeTracker.getMaxServerGraphDataLength()) // Only notify the frontend to append to the historical graph // if both the graphing behavior is enabled and the backend agrees // that the ping is eligible for addition if (updateHistoryGraph) { - this.graphData.push(playerCount) - - // Trim old graphPoints according to #getMaxGraphDataLength - if (this.graphData.length > TimeTracker.getMaxGraphDataLength()) { - this.graphData.shift() - } + TimeTracker.pushAndShift(this.graphData, playerCount, TimeTracker.getMaxGraphDataLength()) } // Delegate out update payload generation diff --git a/lib/time.js b/lib/time.js index 1710644..34c8afd 100644 --- a/lib/time.js +++ b/lib/time.js @@ -10,11 +10,7 @@ class TimeTracker { newPingTimestamp () { const timestamp = new Date().getTime() - this._points.push(timestamp) - - if (this._points.length > TimeTracker.getMaxServerGraphDataLength()) { - this._points.shift() - } + TimeTracker.pushAndShift(this._points, timestamp, TimeTracker.getMaxServerGraphDataLength()) // Flag each group as history graph additions each minute // This is sent to the frontend for graph updates @@ -24,11 +20,7 @@ class TimeTracker { this._lastHistoryGraphUpdate = timestamp // Push into timestamps array to update backend state - this._historicalTimestamps.push(timestamp) - - if (this._historicalTimestamps.length > TimeTracker.getMaxGraphDataLength()) { - this._historicalTimestamps.shift() - } + TimeTracker.pushAndShift(this._historicalTimestamps, timestamp, TimeTracker.getMaxGraphDataLength()) } return { @@ -60,6 +52,14 @@ class TimeTracker { static getMaxGraphDataLength () { return Math.ceil(config.graphDuration / config.rates.pingAll) } + + static pushAndShift (array, value, maxLength) { + array.push(value) + + if (array.length > maxLength) { + array.shift() + } + } } module.exports = TimeTracker