Linear Regression Least Squares Fit
Fit a least-squares line to x/y points and return slope, intercept, R-squared and a prediction function with validation.
Code
export interface Point {
x: number;
y: number;
}
export interface RegressionResult {
slope: number;
intercept: number;
rSquared: number;
predict: (x: number) => number;
}
export function linearRegression(points: readonly Point[]): RegressionResult {
if (!Array.isArray(points) || points.length < 2) {
throw new RangeError("points must contain at least two items");
}
for (const point of points) {
if (!Number.isFinite(point.x) || !Number.isFinite(point.y)) {
throw new TypeError("points must contain finite coordinates");
}
}
const count = points.length;
const meanX = points.reduce((total, point) => total + point.x, 0) / count;
const meanY = points.reduce((total, point) => total + point.y, 0) / count;
let numerator = 0;
let denominator = 0;
let total = 0;
for (const point of points) {
const dx = point.x - meanX;
const dy = point.y - meanY;
numerator += dx * dy;
denominator += dx * dx;
total += dy * dy;
}
if (denominator === 0) throw new RangeError("x values must not all be equal");
const slope = numerator / denominator;
const intercept = meanY - slope * meanX;
const rSquared = total === 0 ? 1 : (numerator * numerator) / (denominator * total);
return { slope, intercept, rSquared, predict: (x) => intercept + slope * x };
}How the snippet works
Linear Regression Least Squares Fit keeps everything in the function linearRegression.
The failure path is explicit — RangeError and TypeError is raised when the guard condition holds.
The result comes back as an object carrying slope, intercept, rSquared.
Points of care
- The guard
denominator === 0short-circuits the flow with an earlythrowwhen its condition holds.
Applying it
The main signature reads export function linearRegression(points: readonly Point[])
The surface worth importing is linearRegression; the helpers around it are private to the snippet.
The call returns slope, intercept, rSquared — destructure what you need at the call site.
Statements that matter
return { slope, intercept, rSquared, predict: (x) => intercept + slope * x };
const meanX = points.reduce((total, point) => total + point.x, 0) / count;
const meanY = points.reduce((total, point) => total + point.y, 0) / count;
Interactive Tools for This Topic
A/B Test Sample Size CalculatorCalculate required per-variant sample size and experiment duration for two-proportion A/B tests from baseline conversion, MDE, alpha, and statistical power.Big-O Complexity VisualizerVisualize and compare algorithm time complexities like O(1), O(log n), O(n), O(n log n), and O(n²). Plot growth curves to understand performance scaling at a glance.SRI Hash GeneratorGenerate Subresource Integrity (SRI) hashes from resource content using SHA-256, SHA-384, or SHA-512, and copy a ready-to-use script tag.Statistics CalculatorCompute count, sum, mean, median, minimum, maximum, range, variance, and standard deviation for a number list.
FAQ
- Does `linearRegression` modify its input?
- No mutation happens — the function reads its input and returns a new value.
- How are precondition violations signaled?
- `RangeError` and `TypeError` is raised at the guard (`denominator === 0`), so invalid state never reaches the main logic.
- Any setup needed beyond the language runtime?
- None — the language runtime is the only requirement. The file defines `linearRegression` at load time.
Report a problem with this exampleOpens a pre-filled issue on GitHub.