Syntax error Sum array of rational numbers and returning the result in simplest form in JavaScript

Sum array of rational numbers and returning the result in simplest form in JavaScript



Problem

We are required to write a JavaScript function that takes in an array of exactly two subarrays with two numbers each.

Both the subarrays represent a rational number in fractional form. Our function should add the rational numbers and return a new array of two numbers representing the simplest form of the added rational number.

Example

Following is the code −

 Live Demo

const arr = [
   [1, 2],
   [1, 3]
];
const findSum = (arr = []) => {
   const hcf = (a, b) => b ? hcf(b, a % b) : a;
   if(!arr.length){
      return null;
   };
   const [n, d] = arr.reduce(([a, x], [b, y]) => [a*y + b*x, x*y]);
   const g = hcf(n, d);
   return g === d ? n / d : [n / g, d / g];
};
console.log(findSum(arr));

Output

Following is the console output −

[5, 6]
Updated on: 2021-04-19T08:17:05+05:30

181 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements