Factorial Calculator

A simple script to calculate the factorial of a number entered by the user.

// ==UserScript==
// @name         Factorial Calculator
// @namespace    http://example.com/factorialcalculator
// @version      1.0
// @description  A simple script to calculate the factorial of a number entered by the user.
// @author       Your Name
// @match        *://*/*
// @license      MIT
// @grant        none
// @locale       en
// ==/UserScript==

(function() {
    'use strict';

    /**
     * This function calculates the factorial of a given number 'n'.
     * The factorial of a number is the product of all positive integers less than or equal to 'n'.
     * For example:
     *     - factorial(5) = 5 * 4 * 3 * 2 * 1 = 120
     *     - factorial(0) = 1 (by definition)
     *
     * @param {number} n - The number to calculate the factorial of. Must be a non-negative integer.
     * @returns {number} The factorial of the input number 'n'.
     * @throws {Error} If the input 'n' is negative, as factorial is only defined for non-negative integers.
     */
    function factorial(n) {
        if (n < 0) {
            throw new Error('Input must be a non-negative integer.');
        }
        
        let result = 1;
        for (let i = 1; i <= n; i++) {
            result *= i;
        }
        return result;
    }

    // Example usage:
    // Prompt the user to enter a number
    let num = parseInt(prompt('Enter a non-negative integer:', ''), 10);
    
    // Ensure valid input and display result
    if (!isNaN(num) && num >= 0) {
        alert('The factorial of ' + num + ' is ' + factorial(num));
    } else {
        alert('Please enter a valid non-negative integer.');
    }
})();