Skip to content

Commit d7e4caf

Browse files
committed
feat: lesson07 make updates to functions
1 parent bb27341 commit d7e4caf

File tree

3 files changed

+30
-4
lines changed

3 files changed

+30
-4
lines changed

lesson_07/conditionals/src/lesson7.ts

Lines changed: 18 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -28,11 +28,25 @@ export function compareStrings(a: string, b: string): number {
2828
* @param n The value for which to compute the factorial.
2929
* @return The factorial of n.
3030
*/
31-
export function computeFactorial(n: number): number {
32-
if (n === 0) return 1;
33-
return n * computeFactorial(n - 1);
31+
32+
export function computeFactorial(n: number): number {
33+
// Factorial is not defined for negative numbers
34+
if (n < 0) throw new Error("not defined");
35+
36+
// Special case: if n is 0, return something different (here, 0)
37+
if (n === 0) return 0;
38+
39+
let result = 1;
40+
41+
for (let i = 2; i <= n; i++) {
42+
result *= i;
43+
}
44+
45+
return result;
3446
}
35-
console.log(computeFactorial(5)); // Output: 120
47+
48+
const number = 5;
49+
console.log(computeFactorial(number));
3650

3751
/**
3852
* Returns an array of the first `n` Fibonacci numbers starting from 1.

lesson_07/package-lock.json

Lines changed: 6 additions & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

package-lock.json

Lines changed: 6 additions & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

0 commit comments

Comments
 (0)