Checking for straight lines in JavaScript

JavascriptWeb DevelopmentFront End TechnologyObject Oriented Programming

We are required to write a JavaScript function that takes in an array of arrays. Each subarray will contain exactly two items, representing the x and y coordinates respectively.

Our function should check whether or not the coordinates specified by these subarrays form a straight line.

For example −

[[4, 5], [5, 6]] should return true.

The array is guaranteed to contain at least two subarrays.

Example

The code for this will be −

const coordinates = [
   [4, 5],
   [5, 6]
];
const checkStraightLine = (coordinates = []) => {
   if(coordinates.length === 0) return false;
   let x1 = coordinates[0][0];
   let y1 = coordinates[0][1];
   let slope1 = null;
   for(let i=1;i<coordinates.length;i++){
      let x2= coordinates[i][0];
      let y2= coordinates[i][1];
      if(x2-x1 === 0){
         return false;
      }
      if(slope1 === null){
         slope1 = (y2-y1) / (x2-x1);
         continue;
      }
      let slope2 = (y2-y1) / (x2-x1);
      if(slope2 != slope1){
         return false;
      }
   }
   return true;
};
console.log(checkStraightLine(coordinates));

Explanation

We determine the slope for each point with the first point if the slope is equal, it’s a straight line, otherwise if one of the points have different slope this means, points are not on the same line.

Output

And the output in the console will be −

true
raja
Published on 20-Nov-2020 17:54:04
Advertisements