DEV Community

avinash-repo
avinash-repo

Posted on

12 way of factorial implementation step by step in js

Certainly, let's break down each function and its implementation:
https://onecompiler.com/javascript/423e78zcb

  1. Recursive Factorial Function:

    • Definition: Calculates the factorial of a given number using recursion.
    • Code:
     function factorial(n) {
         if (n === 0 || n === 1) {
             return 1;
         } else {
             return n * factorial(n - 1);
         }
     }
    
  • Example Usage:

     const result = factorial(5);
     console.log(result);  // Output: 120
    
  1. Iterative Factorial Function:

    • Definition: Computes the factorial using a traditional iterative approach.
    • Code:
     function factorialIterative(n) {
         let result = 1;
         for (let i = 2; i <= n; i++) {
             result *= i;
         }
         return result;
     }
    
  • Example Usage:

     const result1 = factorialIterative(6);
     console.log(result1);  // Output: 720
    
  1. Ternary Recursive Factorial Function:

    • Definition: Utilizes a ternary operator for a concise recursive factorial calculation.
    • Code:
     function factorialTernary(n) {
         return (n === 0 || n === 1) ? 1 : n * factorialTernary(n - 1);
     }
    
  • Example Usage:

     const result2 = factorialTernary(4);
     console.log(result2);  // Output: 24
    
  1. While Loop Factorial Function:

    • Definition: Achieves factorial calculation through a while loop.
    • Code:
     function factorialWhileLoop(n) {
         let result = 1;
         while (n > 1) {
             result *= n;
             n--;
         }
         return result;
     }
    
  • Example Usage:

     const result3 = factorialWhileLoop(4);
     console.log(result3);  // Output: 24
    
  1. ES6 Arrow Function Recursive Factorial:

    • Definition: Implements a concise recursive factorial using an ES6 arrow function.
    • Code:
     const factorialES6 = n => (n === 0 || n === 1) ? 1 : n * factorialES6(n - 1);
    
  • Example Usage:

     const result4 = factorialES6(5);
     console.log(result4);  // Output: 120
    
  1. ES6 Arrow Function Iterative Factorial:

    • Definition: Computes factorial iteratively with an ES6 arrow function.
    • Code:
     const factorialES6Iterative = (n, result = 1) => {
         for (let i = 2; i <= n; i++) {
             result *= i;
         }
         return result;
     };
    
  • Example Usage:

     const result5 = factorialES6Iterative(5);
     console.log(result5);  // Output: 120
    
  1. ES6 Arrow Function Reduce Factorial:

    • Definition: Utilizes the reduce function for factorial calculation.
    • Code:
     const factorialES6Reduce = n => [...Array(n).keys()].reduce((acc, val) => acc * (val + 1), 1);
    
  • Example Usage:

     const result6 = factorialES6Reduce(6);
     console.log(result6); // Output: 720
    
  1. Memoized Recursive Factorial Function:

    • Definition: Memoizes results to optimize recursive factorial calculation.
    • Code:
     const factorialMemoized = (function() {
         const memo = {};
         function factorial(n) {
             if (n === 0 || n === 1) {
                 return 1;
             }
             if (memo[n]) {
                 return memo[n];
             }
             memo[n] = n * factorial(n - 1);
             return memo[n];
         }
         return factorial;
     })();
    
  • Example Usage:

     const result7 = factorialMemoized(5);
     console.log(result7);  // Output: 120
    
  1. Functional Approach Using Array.from and reduce:

    • Definition: Calculates factorial functionally using Array.from and reduce.
    • Code:
     const factorialFunctional = n => Array.from({ length: n }, (_, i) => i + 1).reduce((acc, val) => acc * val, 1);
    
  • Example Usage:

     const result8 = factorialFunctional(5);
     console.log(result8);  // Output: 120
    
  1. Compose Function for a Complex Factorial Implementation:

    • Definition: Uses a composition of functions to calculate and display factorial.
    • Code:
      const compose = (...functions) => input => functions.reduceRight((acc, fn) => fn(acc), input);
      const range = n => Array.from({ length: n }, (_, i) => i + 1);
      const multiply = (a, b) => a * b;
      const factorialComplex = n => compose(
          result => console.log(result),
          numbers => numbers.reduce(multiply, 1),
          range,
      )(n);
    
- Example Usage:
Enter fullscreen mode Exit fullscreen mode
  ```javascript
  factorialComplex(5);  // Output: 120
  ```
Enter fullscreen mode Exit fullscreen mode
  1. Factorial Using BigInt for Larger Numbers:

    • Definition: Handles larger factorials using BigInt data type.
    • Code:
      const factorialUsingMap = n => {
          return Array.from({ length: n }, (_, i) => i + 1)
              .map(number => BigInt(number))
              .reduce((acc, val) => acc * val, BigInt(1));
      };
    
- Example Usage:
Enter fullscreen mode Exit fullscreen mode
  ```javascript
  const result9 = factorialUsingMap(5);
  console.log(result9.toString());  // Output: 120
  ```
Enter fullscreen mode Exit fullscreen mode
  1. Factorial Using Immediately Invoked Function Expression (IIFE) in ES6:

    • Definition: Implements factorial using an IIFE with BigInt for larger numbers.
    • Code:
      const factorialUsingIIFEES6 = ((n) => {
          const calculateFactorial = (num, result = BigInt(1)) => {
              if (num === 0 || num === 1) {
                  return result;
              }
              return calculateFactorial(num - 1, result * BigInt(num));
          };
          return calculateFactorial(n);
      })(5);
    
- Example Usage:
Enter fullscreen mode Exit fullscreen mode
  ```javascript
  console.log(factorialUsingIIFEES6.toString());  // Output: 120
  ```
Enter fullscreen mode Exit fullscreen mode

Certainly. Let's break down each factorial implementation step by step:

  1. Recursive Function (factorial):

    • Base case: If n is 0 or 1, return 1.
    • Recursive case: n! = n * (n-1)!.
    • Example usage: result = factorial(5), outputs 120.
  2. Iterative Function (factorialIterative):

    • Use a loop to multiply numbers from 2 to n.
    • Example usage: result1 = factorialIterative(6), outputs 720.
  3. Ternary Recursive Function (factorialTernary):

    • A concise recursive version using a ternary operator.
    • Example usage: result2 = factorialTernary(4), outputs 24.
  4. While Loop Iterative Function (factorialWhileLoop):

    • Similar to the iterative version but uses a while loop.
    • Example usage: result3 = factorialWhileLoop(4), outputs 24.
  5. ES6 Arrow Function Recursive (factorialES6):

    • An ES6 arrow function equivalent to the recursive version.
    • Example usage: result4 = factorialES6(5), outputs 120.
  6. ES6 Arrow Function Iterative (factorialES6Iterative):

    • An ES6 arrow function equivalent to the iterative version.
    • Example usage: result5 = factorialES6Iterative(5), outputs 120.
  7. ES6 Arrow Function Reduce (factorialES6Reduce):

    • Uses reduce and array methods to calculate factorial.
    • Example usage: result6 = factorialES6Reduce(6), outputs 720.
  8. Memoized Recursive Function (factorialMemoized):

    • Utilizes memoization to store previously calculated results.
    • Example usage: result7 = factorialMemoized(5), outputs 120.
  9. Functional Approach (factorialFunctional):

    • A functional approach using Array.from and reduce.
    • Example usage: result8 = factorialFunctional(5), outputs 120.
  10. Compose Function and Complex Factorial (factorialComplex):

    • Composes functions to display, multiply, and generate a range of numbers.
    • Example usage: factorialComplex(5), displays and returns 120.
  11. Using Map and BigInt (factorialUsingMap):

    • Converts numbers to BigInt to handle larger factorials.
    • Example usage: result9 = factorialUsingMap(5), outputs 120.
  12. IIFE with ES6 Arrow Function and BigInt (factorialUsingIIFEES6):

    • An Immediately Invoked Function Expression (IIFE) using BigInt for larger numbers.
    • Example usage: factorialUsingIIFEES6, outputs 120.

Top comments (0)