Skip to content

Commit d0f341a

Browse files
fix(forecast): hoist regression variables to avoid ReferenceError in trend detection
The costReg, tokenReg, and sessionReg variables were const-declared inside the if (method === 'linear') block but referenced outside it for trend detection. When method was 'linear', the trend detection code at the bottom of the route handler would throw a ReferenceError because those const bindings were not in scope. Hoist the regression computations above the if-block so they're accessible to both the prediction loop and the trend detection code. Guard with a method check to avoid unnecessary computation for non-linear methods.
1 parent 7bca589 commit d0f341a

1 file changed

Lines changed: 8 additions & 4 deletions

File tree

backend/routes/forecast.js

Lines changed: 8 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -332,11 +332,15 @@ router.get("/", wrapRoute("forecast usage", (req, res) => {
332332
const numTokenValues = tokenValues.map(Number);
333333
const numSessionValues = sessionValues.map(Number);
334334

335-
if (method === "linear") {
336-
const costReg = linearRegression(costValues);
337-
const tokenReg = linearRegression(numTokenValues);
338-
const sessionReg = linearRegression(numSessionValues);
335+
// Pre-compute regressions when needed — hoisted so trend detection
336+
// below can reuse them without a redundant linearRegression() call.
337+
// Previously these were const-declared inside the if-block, causing
338+
// a ReferenceError when accessed outside that scope for trend detection.
339+
const costReg = method === "linear" ? linearRegression(costValues) : null;
340+
const tokenReg = method === "linear" ? linearRegression(numTokenValues) : null;
341+
const sessionReg = method === "linear" ? linearRegression(numSessionValues) : null;
339342

343+
if (method === "linear") {
340344
for (let d = 1; d <= forecastDays; d++) {
341345
const futureX = n - 1 + d;
342346
const predCost = Math.max(0, costReg.slope * futureX + costReg.intercept);

0 commit comments

Comments
 (0)