How to use Slope Calculation In Javascript
Define a function that takes an array of coordinates as parameter. Get the x and y coordinates of the first two points from the coordinates array. Compute the slope between the first two points using the formula (y1 – y0) / (x1 – x0). Iterate through the remaining coordinates starting from index 2. For each point, calculate the slope between that point and the first point, and compare it with the initial slope. If slopes are not equal, return false else return true.
Example: To demonstrate checking If It Is a straight line in JavaScript using slope calculation approach.
function checkStraightLine(coordinates)
{
const [x0, y0] = coordinates[0];
const [x1, y1] = coordinates[1];
const slope = (y1 - y0) / (x1 - x0);
for (let i = 2; i < coordinates.length; i++)
{
const [x, y] = coordinates[i];
if ((y - y0) / (x - x0) !== slope)
{
return false;
}
}
return true;
}
const coordinates = [[1,2], [2,3], [3,4], [4,5]];
console.log(checkStraightLine(coordinates));
Output
true
Time complexity: O(n)
Space complexity: O(1)
Check If It Is a Straight Line in JavaScript
JavaScript allows us to check If the given line is a Straight Line or not. There are several methods of checking if the given line is straight or not in JavaScript. Below is an example to understand the problem clearly.
Example:
Input:
points = [[1, 2], [2, 3], [3, 4], [4, 5]]
Output: true
Input:
points = [[2,3], [7, 2] , [-1, 3]]
Output: false
There are several approaches to Check If It Is a Straight Line in JavaScript which are as follows:
Table of Content
- Using Slope Calculation
- Using Matrix Determinant Approach