12 way of factorial implementation step by step in js
Tags: javascript, webdev, beginners, programming
Published: 2024-02-04 03:53:55

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:
     ```javascript
     function factorial(n) {
         if (n === 0 || n === 1) {
             return 1;
         } else {
             return n * factorial(n - 1);
         }
     }
     ```
   - Example Usage: 
     ```javascript
     const result = factorial(5);
     console.log(result);  // Output: 120
     ```

2. **Iterative Factorial Function:**
   - Definition: Computes the factorial using a traditional iterative approach.
   - Code:
     ```javascript
     function factorialIterative(n) {
         let result = 1;
         for (let i = 2; i <= n; i++) {
             result *= i;
         }
         return result;
     }
     ```
   - Example Usage: 
     ```javascript
     const result1 = factorialIterative(6);
     console.log(result1);  // Output: 720
     ```

3. **Ternary Recursive Factorial Function:**
   - Definition: Utilizes a ternary operator for a concise recursive factorial calculation.
   - Code:
     ```javascript
     function factorialTernary(n) {
         return (n === 0 || n === 1) ? 1 : n * factorialTernary(n - 1);
     }
     ```
   - Example Usage: 
     ```javascript
     const result2 = factorialTernary(4);
     console.log(result2);  // Output: 24
     ```

4. **While Loop Factorial Function:**
   - Definition: Achieves factorial calculation through a while loop.
   - Code:
     ```javascript
     function factorialWhileLoop(n) {
         let result = 1;
         while (n > 1) {
             result *= n;
             n--;
         }
         return result;
     }
     ```
   - Example Usage: 
     ```javascript
     const result3 = factorialWhileLoop(4);
     console.log(result3);  // Output: 24
     ```

5. **ES6 Arrow Function Recursive Factorial:**
   - Definition: Implements a concise recursive factorial using an ES6 arrow function.
   - Code:
     ```javascript
     const factorialES6 = n => (n === 0 || n === 1) ? 1 : n * factorialES6(n - 1);
     ```
   - Example Usage: 
     ```javascript
     const result4 = factorialES6(5);
     console.log(result4);  // Output: 120
     ```

6. **ES6 Arrow Function Iterative Factorial:**
   - Definition: Computes factorial iteratively with an ES6 arrow function.
   - Code:
     ```javascript
     const factorialES6Iterative = (n, result = 1) => {
         for (let i = 2; i <= n; i++) {
             result *= i;
         }
         return result;
     };
     ```
   - Example Usage: 
     ```javascript
     const result5 = factorialES6Iterative(5);
     console.log(result5);  // Output: 120
     ```

7. **ES6 Arrow Function Reduce Factorial:**
   - Definition: Utilizes the `reduce` function for factorial calculation.
   - Code:
     ```javascript
     const factorialES6Reduce = n => [...Array(n).keys()].reduce((acc, val) => acc * (val + 1), 1);
     ```
   - Example Usage: 
     ```javascript
     const result6 = factorialES6Reduce(6);
     console.log(result6); // Output: 720
     ```

8. **Memoized Recursive Factorial Function:**
   - Definition: Memoizes results to optimize recursive factorial calculation.
   - Code:
     ```javascript
     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: 
     ```javascript
     const result7 = factorialMemoized(5);
     console.log(result7);  // Output: 120
     ```

9. **Functional Approach Using `Array.from` and `reduce`:**
   - Definition: Calculates factorial functionally using `Array.from` and `reduce`.
   - Code:
     ```javascript
     const factorialFunctional = n => Array.from({ length: n }, (_, i) => i + 1).reduce((acc, val) => acc * val, 1);
     ```
   - Example Usage: 
     ```javascript
     const result8 = factorialFunctional(5);
     console.log(result8);  // Output: 120
     ```

10. **Compose Function for a Complex Factorial Implementation:**
    - Definition: Uses a composition of functions to calculate and display factorial.
    - Code:
      ```javascript
      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:
      ```javascript
      factorialComplex(5);  // Output: 120
      ```

11. **Factorial Using `BigInt` for Larger Numbers:**
    - Definition: Handles larger factorials using `BigInt` data type.
    - Code:
      ```javascript
      const factorialUsingMap = n => {
          return Array.from({ length: n }, (_, i) => i + 1)
              .map(number => BigInt(number))
              .reduce((acc, val) => acc * val, BigInt(1));
      };
      ```
    - Example Usage: 
      ```javascript
      const result9 = factorialUsingMap(5);
      console.log(result9.toString());  // Output: 120
      ```

12. **Factorial Using Immediately Invoked Function Expression (IIFE) in ES6:**
    - Definition: Implements factorial using an IIFE with `BigInt` for larger numbers.
    - Code:
      ```javascript
      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:
      ```javascript
      console.log(factorialUsingIIFEES6.toString());  // Output: 120
      ```

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`.