How to write the factorial function with reduce and range in JavaScript?

JavascriptWeb DevelopmentFront End TechnologyObject Oriented Programming

We are required to write a JavaScript factorial function that takes the help of another helper function, range().

The range function should prepare a range of numbers from 1 to the input number. Then the main function should run an Array.prototype.reduce() function over the range array to calculate the factorial

Example

The code for this will be −

const range = (start, end) => {
   const acc = [];
   for (var i = start; i < end; i++) {
      acc.push(i);
   };
   return acc;
}
const factorial = n => {
   let factors = range(1, Math.abs(n)+1);
   let res = factors.reduce((acc,val) => {
      return acc * val;
   }, 1);
   if(n < 0){
      res *= -1;
   };
   return res;
};
console.log(factorial(5));

Output

And the output in the console will be −

120
raja
Published on 25-Nov-2020 06:56:58
Advertisements