diff --git a/04-recursion/02-unwinding/readme.md b/04-recursion/02-unwinding/readme.md index 785f75f4..0c3e46ed 100644 --- a/04-recursion/02-unwinding/readme.md +++ b/04-recursion/02-unwinding/readme.md @@ -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); @@ -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}`); diff --git a/04-recursion/02-unwinding/sum-up-to-solution.js b/04-recursion/02-unwinding/sum-up-to-solution.js index 45b5ba60..0366e01e 100644 --- a/04-recursion/02-unwinding/sum-up-to-solution.js +++ b/04-recursion/02-unwinding/sum-up-to-solution.js @@ -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) diff --git a/04-recursion/02-unwinding/sum-up-to-test.js b/04-recursion/02-unwinding/sum-up-to-test.js index 0df1a4ec..deb4e136 100644 --- a/04-recursion/02-unwinding/sum-up-to-test.js +++ b/04-recursion/02-unwinding/sum-up-to-test.js @@ -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);