
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Checking for Straight Lines in JavaScript
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
Advertisements