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

Update solution for basic recursion #176

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
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
7 changes: 3 additions & 4 deletions exercises/basic_recursion/solution/solution.js
Original file line number Diff line number Diff line change
@@ -1,8 +1,7 @@
function reduce(arr, fn, initial) {
return (function reduceOne(index, value) {
if (index > arr.length - 1) return value // end condition
return reduceOne(index + 1, fn(value, arr[index], index, arr)) // calculate & pass values to next step
})(0, initial) // IIFE. kick off recursion with initial values
if (arr.length === 0) return initial // end condition
var subset = arr.slice(0, arr.length - 1) // setup recursive call with left subset
return fn(reduce(subset, fn, initial), arr[arr.length - 1]) // pass last element to traverse ltr
}

module.exports = reduce