Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Checking for straight lines in JavaScript
We need to write a JavaScript function that takes an array of coordinate pairs and determines if all points form a straight line. Each subarray contains exactly two items representing x and y coordinates.
Our function checks whether the coordinates form a straight line by calculating and comparing slopes between points.
For example:
[[4, 5], [5, 6]] should return true (slope = 1) [[1, 2], [2, 3], [4, 5]] should return true (all have slope = 1) [[1, 1], [2, 2], [3, 4]] should return false (different slopes)
The array is guaranteed to contain at least two coordinate pairs.
Algorithm
To check if points form a straight line, we calculate the slope between the first point and every other point. If all slopes are equal, the points are collinear.
The slope formula is: slope = (y2 - y1) / (x2 - x1)
Example
const coordinates = [
[4, 5],
[5, 6],
[6, 7]
];
const checkStraightLine = (coordinates = []) => {
if (coordinates.length
Test 1: true
Test 2: false
Test 3: true
Handling Vertical Lines
For vertical lines (where x coordinates are the same), we use Infinity to represent the undefined slope:
const verticalLine = [[2, 1], [2, 3], [2, 5]];
console.log("Vertical line test:", checkStraightLine(verticalLine));
const mixedPoints = [[2, 1], [3, 2], [2, 5]]; // Not a straight line
console.log("Mixed points test:", checkStraightLine(mixedPoints));
Vertical line test: true
Mixed points test: false
How It Works
The algorithm works by:
- Taking the first two points as reference to calculate the expected slope
- For each remaining point, calculating its slope with the first point
- If any slope differs from the reference slope, the points don't form a straight line
- Special handling for vertical lines using
Infinity
Conclusion
This solution efficiently determines if coordinate points form a straight line by comparing slopes. It handles both regular and vertical lines correctly with O(n) time complexity.
