Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix: 04-02 test case causes max call stack exceeded #13

Open
wants to merge 4 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 4 additions & 4 deletions 04-recursion/02-unwinding/readme.md
Original file line number Diff line number Diff line change
Expand Up @@ -10,8 +10,8 @@ Let's look at an example of this. Consider the following function:

```js
function sumUpTo(n) {
if (n === 1) {
return 1;
if (n <= 1) {
return n;
}

return n + sumUpTo(n - 1);
Expand Down Expand Up @@ -50,9 +50,9 @@ We can see this by logging the function calls and the return values:

```js
function sumUpTo(n) {
if (n === 1) {
if (n <= 1) {
console.log(`sumUpTo(${n}) returns 1`);
return 1;
return n;
}

console.log(`sumUpTo(${n}) calls sumUpTo(${n - 1}) + ${n}`);
Expand Down
5 changes: 3 additions & 2 deletions 04-recursion/02-unwinding/sum-up-to-solution.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
function sumUpTo(n) {
// Base case - when n is 1, we return 1
if (n === 1) {
return 1;
// if n is 0 or negative, we handle that case otherwise infinite recursion
if (n <= 1) {
return n;
}

// Recursive case - when n is greater than 1, we return the sum of n and sumUpTo(n - 1)
Expand Down
2 changes: 2 additions & 0 deletions 04-recursion/02-unwinding/sum-up-to-test.js
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
const sumUpTo = require('./sum-up-to');

test('Summing up positive integers', () => {
expect(sumUpTo(5)).toBe(15);
expect(sumUpTo(10)).toBe(55);
Expand Down