584 B
584 B
title, tags, firstSeen, lastUpdated
| title | tags | firstSeen | lastUpdated |
|---|---|---|---|
| factorial | math,algorithm,recursion,beginner | 2017-12-07T14:41:33+02:00 | 2020-12-28T13:49:24+02:00 |
Calculates the factorial of a number.
- Use recursion.
- If
nis less than or equal to1, return1. - Otherwise, return the product of
nand the factorial ofn - 1. - Throw a
TypeErrorifnis a negative number.
const factorial = n =>
n < 0
? (() => {
throw new TypeError('Negative numbers are not allowed!');
})()
: n <= 1
? 1
: n * factorial(n - 1);
factorial(6); // 720