es-next-tools
Version:
A comprehensive utility library for JavaScript and TypeScript that provides a wide range of functions for common programming tasks, including mathematical operations, date manipulations, array and object handling, string utilities, and more.
17 lines (16 loc) • 391 B
JavaScript
/**
* Calculates the factorial of a number.
* @param {number} n - The number to calculate the factorial of.
* @returns The factorial of the given number, or NaN if the number is negative.
* @example
* factorial(5); // 120
*/
export function factorial(n) {
if (n < 0)
return NaN;
let res = 1;
for (let i = 2; i <= n; i++) {
res *= i;
}
return res;
}