Search code examples
javascriptfunctionarea

Function to find area of a rectangle with given cartesian coordinates


Have the function RectangleArea(strArr) take the array of strings stored in strArr, which will only contain 4 elements and be in the form (x y) where x and y are both integers, and return the area of the rectangle formed by the 4 points on a Cartesian grid. The 4 elements will be in arbitrary order. For example: if strArr is ["(0 0)", "(3 0)", "(0 2)", "(3 2)"] then your program should return 6 because the width of the rectangle is 3 and the height is 2 and the area of a rectangle is equal to the width * height.

For example -

Input: ["(1 1)","(1 3)","(3 1)","(3 3)"]
Output: 4
Input: ["(0 0)","(1 0)","(1 1)","(0 1)"]
Output: 1

Solution

  • Below function will work provided you input the correct set of coordinates of rectangle

    function distance(coord1, coord2) {
      console.log(coord1, coord2);
      return Math.sqrt(Math.pow(coord1[0] - coord2[0], 2) + Math.pow(coord1[1] - coord2[1], 2));
    }
    
    function RectangleArea (strArr) {
      if (strArr.length < 4) {
        throw new Error("invalid array passed");
      }
      const numArr = strArr.map(coord => coord.match(/\d/g));
    
      const width = distance(numArr[0], numArr[1]);
      const height = distance(numArr[1], numArr[2]);
      console.log(width, height);
    
      return width * height;
    }